In this post I’ll show you an easy block of code by which you can add and remove a class from list items, not with jQuery, but with pure JavaScript.

Lately, I’ve been trying to write more JavaScript over jQuery. I have no dislike of jQuery and actually use it often, however, it is very, very easy to become reliant on it.

I was recently working on a project where we had a row of buttons. Clicking a button generated a new view via Ajax with some different functionalities. I was asked to make each of the buttons highlight when clicked, only one button at a time being highlighted.

Normally I would do this with jQuery’s addClass/removeClass, but I thought I should sharpen my vanilla JavaScript and opted to do it that way.

It’s pretty simple, here are the results. Just click on the buttons and see.

As you click on a button, a menuActive class is added to that button. When you click on another button, the menuActive class is removed from all buttons and added to the new button clicked. The menuActive class gives a blue box shadow to the button.

Neat effect, eh?

So in my example here is the simple HTML:

<div id="button-row">
  <ul>
    <li class="one-third first post-button"><button>Button 1</button></li>
    <li class="one-third post-button"><button>Button 2</button></li>
    <li class="one-third post-button"><button>Button 3</button></li>
  </ul>
</div>

Next, the CSS:

div#button-row {
  text-align:center;
}

#button-row li {
  list-style-type: none;
}

.post-button button {
  text-align: center;
  height: 100px;
  color: black;
  border: 4px solid black;
  background-color: #f3f3f3;
  border-radius: 10px;
  padding: 2px 10px;
}

.menuActive {
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.05) inset, 0 0 15px #0d6adc;
}

And here is the JavaScript:


var btnContainer = document.getElementById("button-row");
var btns = btnContainer.getElementsByTagName("button");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    (document.querySelector('.menuActive')) ? document.querySelector('.menuActive').classList.remove('menuActive') : '';
    this.classList.add('menuActive');
  });
} 

A simple “for loop” looping through the buttons. An event listener is set up for the click. When a button is clicked, menuActive is first removed from ALL of them, then it is added to the clicked button.

When another button is clicked, menuActive is again first removed from ALL of them, and then added to the clicked button.

No jQuery needed.

Comments