jQuery unveiled: the hide() method

The jQuery's hide() method simply hides an element by setting its display property to none. It also accepts a speed parameter that defines how fast an element should be hidden, and a callback function to be used while the element disappears from view. Here's the code:

hide: function( speed, callback ) {
  if ( speed || speed === 0 ) {
   return this.animate( genFx("hide", 3), speed, callback);

  } else {
   for ( var i = 0, l = this.length; i < l; i++ ) {
    var old = jQuery.data(this[i], "olddisplay");
    if ( !old && old !== "none" ) {
     jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
    }
   }

   // Set the display of the elements in a second loop
   // to avoid the constant reflow
   for ( var j = 0, k = this.length; j < k; j++ ) {
    this[j].style.display = "none";
   }

   return this;
  }
 },

The second loop takes place while the browser is actually making the web page reflow to take into account the change in the state of the affected element.

However, this method poses some accessibility problems. Most screen readers interpret the declaration display:none as its aural equivalent speak: none so that if an element has such a declaration, nothing of its contents will be speak aloud. You can use another approach:

.hidden {
  position: absolute;
  top: -1000em;
}

This approach will be rendered correctly by all of the screen readers. You can use this class with jQuery or, even better, you can use the animate method together with the aforementioned CSS styles.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.