Helium Development

Saved

- Edit All
The benefits of toggling CSS classes with jQuery I've often used this method to hide and show elements on a page, but I've found that most of the time it's a better choice to simply toggle a CSS class and avoid changing inline styles of an element.

Mar 15, 2015

I’ve often used this method to hide and show elements on a page, but I’ve found that most of the time it’s a better choice to simply toggle a CSS class and avoid changing inline styles of an element. Not-so-good way:

// Hide/show an element
$('.some-element').toggle();

// HTML output: 

  Better way:

// Hide/show an element
$('.some-element').toggleClass('active');

// HTML output: 

  With some quick CSS:

.some-element {
  display: none;
}
.some-element.active {
  display: inline-block;
}

There’s a number of benefits, some of which are:

display: block as a default

jQuery doesn’t care about what display value you had set earlier for that element, so when the element is forcefully shown, it will always set to display: block. But, what in the case where you’re using an inline element? If you simply toggle a class, you can set exactly how you want that “active” element to behave.

No inline styles

When using this method, you keep JavaScript from forcing inline-styles on your elements, which, by default, hold more weight than other CSS declarations (notwithstanding the !important flag). This can cause some unexpected behavior when you try, with CSS, to change the display type. This isn’t a hard fast rule for me, but it seems that 90% of the time I do use .toggle() I end up switch later anyway. A few extra lines of CSS and you’ll save yourself some headache later on.

I've often used this method to hide and show elements on a page, but I've found that most of the time it's a better choice to simply toggle a CSS class and avoid changing inline styles of an element.