I have a <div>
, and I want to toggle its classes on hover.
Here is my code:
function a(){ this.classList.toggle('first'); this.classList.toggle('sec'); } document.querySelector('#container').addEventListener('click', a );
I know there is no problem in my html or css. It is just that I have to change and put something in place of click
, but I don't know what.
Please help!!
Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript ...
Toggle Class Toggle between adding a class name to the div element with id="myDIV" (in this example we use a button to toggle the class name).
We can do that by using the HTML label tag and HTML input type = checkbox. HTML code: The HTML code is used to create a structure of toggle switch. Since it does not contain CSS so it is just a simple structure.
The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.
Hover event is called "mouseenter" instead of "click".
<script type="text/javascript"> function a(){ this.classList.toggle('first'); this.classList.toggle('sec'); } document.querySelector('#container').addEventListener('mouseenter', a ) document.querySelector('#container').addEventListener('mouseleave', a ) </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With