Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a class on hover remove class on second hover

I want to add a class on hover but not remove it when mouse leaves. Instead it must be removed on the second mouse hover. So on mouse hover add class. Mouse leaves class remains. Mouse hovers again class is removed.

This code adds the class but if the mouse leaves the class is removed which is not what I’m trying to achieve.

jQuery('.menuButton').hover(function(){
  jQuery('.mainMenuDrop').addClass('show')
}, function() {
  jQuery('.mainMenuDrop').removeClass('show')
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To achieve your requirement of add on first entry and remove on second entry, you can change your existing code:

jQuery('.menuButton').hover(function(){
  jQuery('.mainMenuDrop').addClass('show')
}, function() {
  jQuery('.mainMenuDrop').removeClass('show')
});

to use .toggleClass

jQuery('.menuButton').hover(function(){
  jQuery('.mainMenuDrop').toggleClass('show')
}, function() {
  // nothing here
});

As jquery .hover binding is just syntax for mouseenter and mouseleave and you don’t need mouseleave, this can be simplified to:

jQuery('.menuButton').on("mouseenter", function() {
  jQuery('.mainMenuDrop').toggleClass('show');
});
div { border: 1px solid black; padding: 20px; width: 100px; }
.show { background-color: pink; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='menuButton'>point at me</div>
<div class='mainMenuDrop'>changes here</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading