1

everyone!

So here's the problem. I am doing a Frontend Mentor challenge and I applied a hover effect on a object in CSS.

.numero-avaliacao a:hover {
    background-color: hsl(217, 12%, 63%);
    color: white;
}

hover effect working

And it worked fine. However, after I applied a javascript event on these objects, the hover effect dissapears for all of them. All I did with the JS was change the background color and the color of the objects. However, it seems that somehow this affects the hover effect.

function selecionarNota() {

    if (this.style.backgroundColor == 'rgb(251, 116, 19)') {

        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

    } else {

        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
            console.log('Teste 2!');
        }

        this.style.backgroundColor = 'rgb(251, 116, 19)';
        this.style.color = 'white';

    }
}

I worked out this problem by using mouseover and mouseleave on JS, but I would really like to understand what is happening so I can fix it and be able to use the hover effect as well.

2
  • 1
    style attribute settings will override the settings in a stylesheet (unless you employ !important). Is that the problem here? Commented Nov 17, 2022 at 20:51
  • Yeah! I didn't know about inline styles having higher precedence than external css stylesheets. Problem solved! :D Commented Nov 17, 2022 at 22:07

1 Answer 1

2

Inline styles have a higher precedence then you external css stylesheet.

When your :hover from your stylesheet is triggered it can't override your via javascript defined inline style for background-color and color.

You could add an !important tag after your declaration in your stylesheet.

.numero-avaliacao a:hover {
   background-color: hsl(217, 12%, 63%) !important;
   color: white !important;
}

This should do the trick.

Another option would be to add another class to your elements via javascript instead of setting inline style.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.