Sponsored by Gluten Free Waffles and Sliced Bananas

Tuesday, February 19, 2013

Adding and Removing Classes Using jQuery's .toggleClass()

8:26 AM Posted by Tyson Nero 1 comment
I wrote a function to toggle the states of some navigation buttons on a form submission page that has multiple tabs.

If you are on the first tab, the Previous button is disabled.

If you are on the last tab, the Next button is disabled and the Save button turns green.

My first implementation was around 20 lines and had two sets of if/else blocks. There wasn’t anything truly wrong with it, but I felt it could be refactored by somehow removing the need for if/else conditions.

So, I did a little research and found that jQuery has a toggleClass function that you can pass in a Boolean value to determine whether the class should be added or removed. I then converted my if/else conditions into single line expressions that returned a Boolean which I could then pass to the toggleClass function. Here is the final code.

The key in refactoring this code was leveraging an existing function from a library that did the work for me. At first, I didn't know it existed, but after a Google search and reading the jQuery documentation, I was able to implement and refactor in little time.