The benefits of toggling CSS classes with jQuery

Mar 15, 2015 | Blog

The very popular .toggle() method in jQuery isn't always the best option.

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

// HTML output: 

  Better way:

// Hide/show an element

// HTML output: 

  With some quick CSS:

.some-element {
  display: none;
} {
  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.

Recent Articles

Introducing Relatable

Keeping things organized within a Shopify store can be hard, so we built Relatable to help with that.

Why we use Cloud66 to launch Ruby on Rails apps

We use Cloud66 for deploy Ruby on Rails apps, and we love it.

5 Common Pitfalls when Developing a Shopify Theme

Learn some tips on developing Shopify themes and some pitfalls to avoid. Build Shopify themes that perform and are easy to update and edit.

How to create a Shopify email link from your theme navigation

Add an email link to your Shopify website from within your theme using your current link list in navigation.

How to flag Shopify products as "new" by date

Here's a quick way to mark a product as being new by the date it was added to your Shopify store.