How would that code be in JQuery in pure JS?

4

This code snippet is to activate the .nav class but in JS there are some options like:

classList.toggle('active-nav') 

But what about to disable when you click pure JS again? follow script with Jquery!

$(document).ready(function(){
    $('.nav').click(function(){
        $(this).addClass('active-nav').siblings().removeClass('active-nav');
    });
 });
    
asked by anonymous 01.11.2017 / 16:05

3 answers

2

First, Toggle is not to activate a class. What it does is add a class, if it is not already added. And if it is already added it removes it.

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

I've added an example below so you can see in practice how this 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>
    
01.11.2017 / 16:31
4

As you mentioned, the native JavaScript has toggle that can help here. A version of this code in modern JavaScript might look 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 of toggle to compare the iterated elements with the clicked.

    
01.11.2017 / 16:42
2

One 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>
    
01.11.2017 / 16:47