3

I love using the hide() and show() methods, but I've come across someone's scripting where they never use it.
Instead I see them using attr() for anything related to display.

$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");

Is this just purely preferential?
Or is it more beneficial to use one vs the other?

coffeemonitor
  • 12,780
  • 34
  • 99
  • 149

3 Answers3

3

There is a difference. Take .hide() for example:

This is roughly equivalent to calling .css('display', 'none'), (...)

visibility and display are two different CSS properties. Using visibility: hidden; leaves space for the element in the layout but does not display it.

Another (minor) difference is that calling .attr("style", '...') will override all other styles that might be set on the element.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Hide() and show() effectively remove the element from the source HTML.

Visibility rules only affect whether or not you can see the elements' contents; the space they take up is still reserved, and becomes a blank spot.

sichinumi
  • 1,835
  • 3
  • 21
  • 40
1

There are differences for sure. The show() and hide() methods allow you to use animations if you'd like by setting a duration for the show or hide. Also, hide will keep track of the current display settings (inline, block, etc). http://api.jquery.com/hide/

Using .css('display', 'none') or .css('display', 'block') is probably quicker, but it does provide less functionality.

When you use show()/hide() or .css() to control display is preferential based on what you're trying to accomplish.

One more note. TheDramaLama said that hide() removes the element from the source code. I think what TheDramaLama meant is that it removes it positionally, but it still remains in the source code (aka the DOM).

James
  • 3,051
  • 3
  • 29
  • 41
  • Right, bad phrasing on my part. :) I meant it in reference to taking up space on the page, as it effectively "disappears" the element. – sichinumi Jun 01 '11 at 21:17