change a class:hover background-color with js

1.3k views Asked by At

I have read quite a few articles but still couldn't figure out. Tried lots of methods they provided but still no luck.

I have this in my html

<a href="report.html" class="btn btn-success btn-lg">Button 1</a>

this is what happens to css when hovered

.btn-success:hover, 
.dropdown-toggle.btn-success {
  background-color: yellow;
}

I want to change the background color to blue using js.

4

There are 4 answers

0
XuChu LIU On

I did not know why you turn to js as css is the best choice for what you need. I guess you might find the css for the link is somehow "tricky": it needs to written in the order of "lvha", i.e. a:link, a:visited, a:hover and a:active

0
Craig Harshbarger On

I'm not sure why you'd need to do this with js when you could just change it in your CSS. But if you must you could just add a class to the element using

$('.btn-success').addClass('hoverClass');

And in your CSS

.hoverClass:hover {
    background: green;
}
3
BufferOverflow On

There are two Javascript events you need, the «onmouseover», that is triggered when the mouse move over the link, and the «onmouseout», that is triggered when the mouse moves aways from the link. I wrote a short example to you.

<html>
    <head>
            <script type="text/javascript">
                    function hoverIn ( element )
                    {
                            element.style.background = "blue";
                    }

                    function hoverOut ( element )
                    {
                            element.style.background = "none";
                    }
            </script>
    </head>
    <body>
            <a href="report.html" onmouseover="hoverIn ( this );" onmouseout="hoverOut ( this );">Click Me</a>
    </body>

0
luckyape On

You can achieve this by changing the class assignment.

First give the link an ID so we can isolate it within the dom.

<a href="report.html" id="myButton" class="btn btn-success btn-lg">Button 1</a>

To change the appearance of that link you could change the class to btn btn-primary btn-lg", the default value for 'btn-primary' is blue.

document.getElementById("myButton").className = "btn btn-primary btn-lg";