Difference between jQuery’s .hide() and setting CSS to display: none
Which am I better off doing? .hide()
is quicker than writing out .css("display", "none")
, but what’s the difference and what are both of them actually doing to the HTML element?
Solution 1:
From the jQuery page about .hide():
"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline."
So if it's important that you're able to revert to the previous value of display
, you'd better use hide()
because that way the previous state is remembered. Apart from that there's no difference.
$(function() {
$('.hide').click(function(){
$('.toggle').hide();
setDisplayValue();
});
$('.show').click(function(){
$('.toggle').show();
setDisplayValue();
});
});
function setDisplayValue() {
var display = $('.toggle')[0].style.display;
$('.displayvalue').text(display);
}
div {
display: table-cell;
border: 1px solid;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<button class="hide">Hide</button>
<button class="show">Show</button>
</p>
<div class="toggle">Lorem Ipsum</div>
<p>
The display value of the div is:
<span class="displayvalue"></span>
</p>
Solution 2:
.hide()
stores the previous display
property just before setting it to none
, so if it wasn't the standard display
property for the element you're a bit safer, .show()
will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.
Solution 3:
Looking at the jQuery code, this is what happens:
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}
return this;
}
},
Solution 4:
They are the same thing. .hide()
calls a jQuery function and allows you to add a callback function to it. So, with .hide()
you can add an animation for instance.
.css("display","none")
changes the attribute of the element to display:none
. It is the same as if you do the following in JavaScript:
document.getElementById('elementId').style.display = 'none';
The .hide()
function obviously takes more time to run as it checks for callback functions, speed, etc...