The problem has already been explained in the other answer, which suggests you to change the event click
by mouseover
. If you want something to happen when you pass the mouse then it has to be the mouseover
event. This way each time you hover over the element, it changes the ativo
class permanently, so even if you hover the mouse over all the elements, the class stays.
However, the code to drop and remove the ativo
class is more complicated than it should be. Referring to documentation will see that each element has a classList
property that allows you to modify the class list in a simple way. The methods relevant to the problem are:
-
classList.add
- Adds another class to the element
-
classList.remove
- Removes the indicated class from the list of element classes
Using this the code that comes within the event would look like this:
btns[i].addEventListener("mouseover", function() {
var current = document.getElementsByClassName("ativo")[0]; //apanhar o ativo
current.classList.remove("ativo"); //remover a classe nele
this.classList.add("ativo"); //adicionar a classe ativo naquele onde tem o mouse
});
The two initial html element searches can also be simplified into one using querySelectorAll
forcing you to only pick elements of class botao
within div777
:
var btns = document.querySelectorAll("#div777 .botao");
Example with all that was mentioned:
var btns = document.querySelectorAll("#div777 .botao");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("mouseover", function() {
var current = document.getElementsByClassName("ativo")[0];
current.classList.remove("ativo");
this.classList.add("ativo");
});
}
.botao {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
font-size: 18px;
}
.ativo, .botao:hover {
background-color: #666;
color: white;
}
<div id="div777">
<a class="botao">1</a>
<a class="botao ativo">2</a>
<a class="botao">3</a>
<a class="botao">4</a>
<a class="botao">5</a>
</div>