Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason why one would call hide() before show()?

Tags:

jquery

Why would one want to call hide() before show() ? I'd like to know this before i optimize this with method chaining..

function ShowSomething() {
  jQuery("something").hide();
  jQuery("something").show();
}
like image 675
trinity Avatar asked Mar 23 '23 22:03

trinity


2 Answers

When calling hide() the initial value of that element's display is stored for when show() is called, that initial value is put back in place. If no initial value is set, then show() will set display:block.

So, if an element was originally display:inline, but (let's say) .css("display","none") was called on that element, it would be hidden with no initial property saved. When we show() this element again it will be given display:block - not it's initial value of inline which is what it would be given if we'd used hide().

To summarize: hide() will preserve the original display value ready for show() to use

Source: The jQuery hide() documentation

like image 162
George Avatar answered Apr 09 '23 18:04

George


There's no difference in the output if that was chained, other than jQuery will actually perform the DOM lookup twice on the non-chained version.

In terms of performance, non-chaining is actually 24% slower, as shown below:

jsperf

See my JSPerf

like image 34
mattytommo Avatar answered Apr 09 '23 20:04

mattytommo