Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I expect to toggle an element's visibility: should I start with class="..." or style="..."?

Tags:

javascript

css

If I have an element on a web page that I expect to be showing and hiding quite a bit using javascript, which would be the most appropriate way to set it as initially invisible?

<div class="hidden">...</div>

or

<div style="display: none;">...</div>

Using class="..." is preferable to style="..." in most cases, but I'm not convinced it's the best fit in this case. Semantically, my element isn't a hidden element, it's just one that will start off hidden when the page first loads. As I'm using jQuery's show() and hide() methods, it means it'll often be in this state:

<div class="hidden" style="display: block;">...</div>

.. which to me is plainly nonsense.

On the other hand, using an in-line style="display: none;" feels somehow hacky and hard-coded.

I'm aware that either method will work perfectly and the user will never be any the wiser, but which pattern violates design principles the least?

like image 661
teedyay Avatar asked Oct 30 '09 15:10

teedyay


2 Answers

Call the style initially-hidden. It accurately conveys the information, and makes sense if you were to ever query for that style using jQuery.

like image 159
John Calsbeek Avatar answered Oct 04 '22 22:10

John Calsbeek


I think if you're going to toggle by changing display around from "" to "none", you should use style. If you're going to toggle by changing class from "hidden" to "", you should use class. In other words, be consistent.

like image 43
Brian Schroth Avatar answered Oct 04 '22 22:10

Brian Schroth