Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery show() and hide() vs classes with display:block / none

Tags:

jquery

css

Just out of curiosity, which of these two techniques is more "valid" to use?

I had a discussion with my supervisor and he told me that I should create two classes with display:block/none and assign them to elements using jQuery, rather than using jQuery's own functions show/hide.

I had the impression that show/hide are widely used functions that work without any issues and they were made to make our lives easier by not forcing us to assign classes.

like image 410
Peter Avatar asked Nov 01 '22 10:11

Peter


2 Answers

You can use such CSS classes to initially hide element on the page to show it later with jQuery.show(). Anyway jQuery.show() sets the style property directly so the browser don't need to lookup through CSS declaration to find a class each time you assign it. So I believe it will work faster and also is more convenient to developer. By the way the code with show/hide is also more readable.

Just compare

$username.hide();

to

$username.addClass('hidden');

Seems the code is more readable, so that it's more maintainable, therefore it's cheaper for customer to support it... and so on.

like image 61
Eugene Naydenov Avatar answered Nov 15 '22 08:11

Eugene Naydenov


They are the same - show() and hide() just switches between display: block (or inline, inline-block, etc) and display: none or similar. Using these or using simple classes to switch between those styles are both perfectly "valid".

The main difference is that show() and hide() support jQuery animations out of the box. Also, classes do not add inline CSS, whereas show() and hide() do (inline html to override whatever the initial display value is). Depending on your use case this may or may not be convenient.

show() and hide() also cache the initial display value so if you hide() an element and then show() it, it will remember what the original display value was (which means it's more flexible since you don't need unique visible classes for elements with different types of display values).

like image 36
Ennui Avatar answered Nov 15 '22 08:11

Ennui