Saturday, July 9, 2011

Showing and Hiding Elements with jQuery

The syntax for showing, hiding an element (or toggling show/hide) is:

$("#myElement").hide("slow", function() {
// do something once the element is hidden
}

$("#myElement").show("fast", function() {
// do something once the element is shown
}

$("#myElement").toggle(1000, function() {
// do something once the element is shown/hidden
}

Remember that the "toggle" command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for "speed" represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.

You can also specifically choose to fade an element in or out, which is always done by animation:

$("#myElement").fadeOut("slow", function() {
// do something when fade out finished
}

$("#myElement").fadeIn("fast", function() {
// do something when fade in finished
}

To fade an element only partially, either in or out:
$("#myElement").fadeTo(2000, 0.4, function() {
// do something when fade is finished
}

 The second parameter (0.4) represents "opacity", and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a "callback function") will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.

No comments:

Post a Comment