skip to Main Content

I set a toggle so when I click the buttons, the button gets the ‘selecionado’ class and change the border color. But when I hover and click, the color remains with the hover color until I remove the mouse.
How do I change it in a way that when I click, the color of the ‘selecionado’ class appears instantly like a priority over the hover color ?

This is what happens

Javascript :

const botaops = document.querySelector("#IdProntoSocorro")
const botaoEnf = document.querySelector("#IdEnfermaria")
const botaoAmb = document.querySelector("#IdAmbulatorio")

botaops.addEventListener("click", function() {
    botaops.classList.toggle("selecionado");
});

botaoEnf.addEventListener("click", function() {
    botaoEnf.classList.toggle("selecionado");
});

botaoAmb.addEventListener("click", function() {
    botaoAmb.classList.toggle("selecionado");
});

CSS :

button:hover {
    border: 3px solid rgb(129, 129, 129);
    background: red;
}

.selecionado{
    border: 3px solid rgb(18, 101, 255);
}

Color of the click to be superimposed over the Hover effect at the time of the click !

2

Answers


  1. Increase the specificity of the second rule:

    button.selecionado {
        border: 3px solid rgb(18, 101, 255);
    }
    
    Login or Signup to reply.
  2. Add :not(.selecionado) to the hover selector so that it only takes effect when the class isn’t active.

    Note that a .click handler will only take effect when you release the mouse. If that’s too late for you, and you want it to take effect when you initially press the mouse, use mousedown instead.

    const botaops = document.querySelector("#IdProntoSocorro")
    botaops.addEventListener("mousedown", function() {
      botaops.classList.toggle("selecionado");
    });
    button:hover:not(.selecionado) {
      border: 3px solid rgb(129, 129, 129);
      background: red;
    }
    
    .selecionado {
      border: 3px solid rgb(18, 101, 255);
    }
    <button id="IdProntoSocorro">click</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search