Swap class with javascript or jquery

Asked

Viewed 17,232 times

2

I have an html menu with a class menu-disable which is when it’s closed, I need to change this class to menu-active which will be when it’s open.

I don’t know much about javascript and I needed to make a script either in javascript or in jquery to change the class in html.

How could I do that? Someone can help me ?

  • You can better explain the functionality you are looking for?

  • I have a menu in html with a menu-disable class that is when it is closed, I need to change this class to menu-active that will be when it is open. So I need a function to make this class change with onclick.

  • uses the functions of jQuery addClass(') and removeClass(') or toggleClass('')

2 answers

6


To give you something to learn take a look at this example:

function trocaClasse(elemento, antiga, nova) {
    elemento.classList.remove(antiga);
    elemento.classList.add(nova);
}

setTimeout(function() {
    var div = document.querySelector('div');
    trocaClasse(div, 'azul', 'verde');
}, 2000);
div {
    padding: 50px;
	transition: background-color 1s;
}

.azul {
    background-color: #00b;
}

.verde {
    background-color: #0b0;
}
<div class="azul"></div>

jsFiddle: https://jsfiddle.net/xkftLzuj/

In the example I created a function with 3 parameters, after 3 seconds there is a class change with a CSS transition. I also used a native method, part of the classList native API. Assim podes adicionar e remover classes a um dados elemento. Podes ainda usar o.toggle('uma_class');` which is like a switch, strip and put the class every time you run.

using an event

You can do similar things with events calling this function. Often you don’t need 2 classes, but only one. The absence of the class already does what is intended, one of the states.

Another example, similar to the one above but with events:

var menu = document.querySelector('div.menu');
var botao = document.querySelector('button#interruptor');
botao.addEventListener('click', function() {
    var aberto = menu.classList.contains('abrir');
    menu.classList.toggle('abrir');
    this.innerHTML = aberto ? 'abrir' : 'fechar';
});
.menu {
    padding: 50px;
    margin-top: -100px;
    transition: margin-top 1s;
    background-color: #ccf;
    margin-bottom: 10px;
}

.abrir {
    margin-top: 0px;
}
<div class="menu"></div>
<button id="interruptor" type="button">abrir</button>

In this example I use the .addEventListener to know when a click occurs and then the toggle to change the class. The this.innerHTML = aberto ? 'abrir' : 'fechar'; is to swap the button text (which is the this within that callback). I also use the .contains to know if the element has a given class...

jsFiddle: https://jsfiddle.net/xkftLzuj/1/

I hope I gave you something to use on your problem!

  • 1

    @Sergio Thank you very much, helped your code and your tips!

2

I’m only going to add one, Sergio’s answer has already killed the question with great solutions.

I believe that in this case there is no need to exchange classes, .menu-disable may not even exist.

The element (the contents of the menu) can have a display:none initially and you will only use Javascript to add/remove a class that makes it visible.

var $menu        = document.querySelector('nav'),
    $menuContent = document.querySelector('nav ul');

$menu.addEventListener('click', function(event){
  if(event.target == $menuContent)
    return; // Para evitar fechar o menu quando clicar no 'conteúdo'.
  
  $menuContent.classList.toggle('active');
}, false);
nav {
  border: 1px solid #ccc;
  padding: 6px
}

nav ul {
  display: none /* Inicialmente o conteúdo do menu não é exibido */
}

nav ul.active {
  display: block /* Somente quando a classe 'active' estiver presente ele será mostrado. */
}
<nav>
  Menu
  <ul>
    conteúdo
  </ul>
</nav>

If at a certain point there is need to know if the menu is open or not, you can use classList#contains(), for example:

if($menuContent.classList.contains('active')){
  // Está aberto.
} else {
  // Está fechado.
}

Finally, I have a habit of using classList on account of the support I give. But it is worth noting that not all browsers have this implemented property, as can be seen on that website. Fortunately the Mozilla people made available an implementation if you want to use classList in a browser without support for this feature.

Browser other questions tagged

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