user2513846
user2513846

Reputation: 1236

how to rewrite jQuery ToggleClass and if/else code into vanilla JS?

I have a small jQuery code for handling some toggle class and HTML5 local-storage and I would like to convert it into a modern vanilla JS code. I have to say I have no clue where to start.

Can someone by any chance show me the correct approach for a modern JS code for this? I would really appreciate it.

example demo: http://jsbin.com/wimojapowo/1/edit?html,css,js,output

$('#container').toggleClass(localStorage.toggled);

$('.bar-toggle').on('click', function() {
  //localstorage values are always strings (no booleans)  
  if (localStorage.toggled != "with_toggle") {
    $('#container').toggleClass("with_toggle", true);
    localStorage.toggled = "with_toggle";
  } else {
    $('#container').toggleClass("with_toggle", false);
    localStorage.toggled = "";
  }
});

Upvotes: 1

Views: 134

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337646

Firstly note that your jQuery example is more complicated than it needs to be. You can just do this:

$('.bar-toggle').on('click', function() {
  $('#container').toggleClass("with_toggle", localStorage.toggled != "with_toggle");
  localStorage.toggled = localStorage.toggled == "with_toggle" ? '' : 'with_toggle';
});

To convert this to plain JS you can use the classList.toggle() method:

document.querySelectorAll('.bar-toggle').forEach(function(el) {
  el.addEventListener('click', function() {
    this.classList.toggle("with_toggle", localStorage.toggled != "with_toggle");
    localStorage.toggled = localStorage.toggled == "with_toggle" ? '' : 'with_toggle';
  });
})

More info on classList at MDN

Upvotes: 3

Related Questions