What would this Jquery code look like in pure JS?

Asked

Viewed 269 times

4

This code snippet is to activate the . Nav class but in JS it has some options like:

classList.toggle('active-nav') 

but to deactivate when clicking again on pure JS? follows script with Jquery!

$(document).ready(function(){
    $('.nav').click(function(){
        $(this).addClass('active-nav').siblings().removeClass('active-nav');
    });
 });

3 answers

4

As you rightly pointed out, native Javascript has the toggle which can help here. A version of this code in modern Javascript could be like this:

window.onload = function() {
  var navs = [].slice.call(document.querySelectorAll('.nav'));

  function toggle(clicked) {
    return function() {
      navs.forEach(el => el.classList.toggle('active-nav', el == clicked));
    }
  }
  navs.forEach(el => el.addEventListener('click', toggle(el)));
}
div.nav {
  display: inline-block;
  padding: 10px 30px;
  background-color: #eee;
  transition: background-color .6s;
  cursor: pointer;
}

div.nav.active-nav {
  background-color: #ccf;
}
<div class="nav">A</div>
<div class="nav">B</div>
<div class="nav">C</div>
<div class="nav">D</div>

The idea is to use the second argument from toggle to compare the iterated elements with the clicked.

2


Firstly, Toggle does not serve to activate a class. What it does is to add a class if it is not already added. And if it’s already added he removes it.

To remove you use .remove('nomeDaClasse'), and stop adding .add('nomeDaClasse').

I added an example below, for you to see in practice how it works:

function trocaClasse() {
  var texto = document.getElementById("texto");
  texto.classList.toggle('ativo');
}

function addClasse() {
  var texto = document.getElementById("texto");
  texto.classList.add('ativo');
}

function removeClasse() {
  var texto = document.getElementById("texto");
  texto.classList.remove('ativo');
}
.ativo {
  color: red;
}
<button onClick="trocaClasse()">Testar - Toggle</button>
<button onClick="addClasse()">Testar - ADD</button>
<button onClick="removeClasse()">Testar - Remove</button>

<br>

<span id="texto" onClick="trocaClasse()">Clique no texto para trocar a cor</span>

2

A solution would be:

(function(){
   obj = document.getElementsByClassName("nav");
   for(x=0;x<obj.length;x++){
      (function(index){
         obj[x].addEventListener("click", function(){
            this.className += " active-nav";
            for(j=0;j<obj.length;j++){
               if(index != j) obj[j].classList.remove("active-nav");
            }
         });
      })(x);
   }
})();
div{
  display: block; width: 30px; height: 30px; border: 1px solid #ddd; line-height: 30px; text-align: center; cursor: pointer;
}

.active-nav{
  background: red;
}
<div class="nav">1</div>
<br />
<div class="nav">2</div>
<br />
<div class="nav">3</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.