jQuery: Effects (Part 1)

Objectives

  • Hide and Show Effects
  • Fading Effect
  • Callback Function

Hide and Show

The Hide and Show effect is very easy and am sure we already used Hide a couple times in the previous posts. The syntax of Hide and Show is the same and very easy, it’s the following:

$(selector).hide(speed);
$(selector).show(speed);

Now let’s use it in an example:

$("#buttonOne").click(function(){
    $("h3").hide(1000); // You can also set the speed in milliseconds or 'fast' or 'slow'
});

$("#buttonTwo").click(function(){
    $("h3").show();
});

And finally, toggle() :

$("button").click(function(){
    $("p").toggle();
});

Fading

If you want an effect of something hidden to fade in:

$("button").click(function(){
    $("#div1").fadeIn();
    $("#div2").fadeIn("slow");
    $("#div3").fadeIn(3000);
});

If you want to something that is shown to fade, then use fadeOut() :

$("button").click(function(){
    $("#div1").fadeOut();
    $("#div2").fadeOut("slow");
    $("#div3").fadeOut(3000);
});

And of course if you want it fade out on first click and then to fade in on the second click or vice versa,  then use fadeToggle() :

$("button").click(function(){
    $("#div1").fadeToggle();
    $("#div2").fadeToggle("slow");
    $("#div3").fadeToggle(3000);
});

Now, there is something called opacity(the transparency-level) which we can use fadeTo() :

 $("button").click(function(){
    $("#div1").fadeTo("slow", 0.15);
    $("#div2").fadeTo("slow", 0.4);
    $("#div3").fadeTo("slow", 0.7);
});

So div 1 is now 0.15, div 2 is now 0.4, and div 3 is now 0.7(1 = no transparency).


Callback

Statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This why we use “callback”, in the normal effects, we specify speed, sometimes opacity and that’s it, but here is what callback does:

$("button").click(function(){ // When button is clicked run this function
    $("p").hide("slow", function(){ /* hide the p element slowly AND when you are DONE, alert.*/
        alert("The paragraph is now hidden");
    });
});

So here we added a parameter called function, which says: “after you have finished this effect 100%, do this”.


 

For more effects go to: jQuery Effect Methods

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s