+ 2

How can I set the :hover and :active styles via JavaScript?

23rd Jul 2017, 12:25 AM
Erik Johanson
Erik Johanson - avatar
2 odpowiedzi
+ 3
lets say ur css is .myButton:hover { background-color: #ABC } u can do this to your html <button class="myButton" onmouseover="banana()"> and then on ur vanilla js function banana() { document.getElementsByClassName("myButton").style.backgroundColor = "#ABC" } or if u use jquery it would be much easier, u dont need to put the onmouseover attribute in ur html $(".myButton").on("mouseover", () => { $(this).css("background-color", "#ABC") })
23rd Jul 2017, 1:31 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 2
You cannot target pseudo classes with JS, as you target an element basic state, with applying some values to 'style' attribute... But you can access css object dynamically and write new declaration overiding oldest declaration, but this is tricky and not very efficient. However, you can also workaround by defining classes on wich you define the pseudo classes and set class name dynamically with JS: <div id="myDiv">test</div> <style> .myCustomHover:hover { color:red; } .myCustomActive:active { background:yellow; } </style> <script> var myDiv = document.getElementById('myDiv'); myDiv.classList.add('myCustomHover'); myDiv.classList.toogle('myCustomActive'); myDiv.classList.remove('myCustomHover'); if (myDiv.classList.contains('myCustomActive') myDiv.classList.remove('myCustomActive'); /* ... and so on */ </script>
23rd Jul 2017, 12:56 AM
visph
visph - avatar