How to remove / switch the hover class to an element (which translates when clicked) without having to move the mouse again?

If you click and do not move the mouse, you will see that the color of the button remains red! What I want to accomplish is that after you click and do not move the mouse, it still removes / switches the .hover class.

JsFiddle example

 $(function() { var $Btn = $('.button'); $Btn.hover(function() { $(this).toggleClass("hover"); }); $Btn.on("click", function() { $(this).toggleClass('active') $('.move').toggleClass('angle'); }); }); 
 .move { border: 1px solid #000000; padding: 10px; transition: transform .2s ease; /* have noticed issue is in "transition" */ } .button.hover { color: red; } .angle { transform: translate(100px, 0); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="move"> <button class="button">on click still red?</button> </div> 
+4
jquery css css3 css-transitions transition
source share
1 answer

The element retains the hover class even after clicking the button (and the container is translated), because the browser does not seem to cause a freeze (or mouse) until the mouse is moved.

One way to fix this is to remove the hover class inside the button's click event handler. But for this you need to change the code of the hover event handler to specifically add the class when you hover over the mouse (hover) and delete it with the mouse (hover-out). This is necessary because according to the current code, although the hover class is deleted in the click event handler, it switches back to the moment the mouse moves again (because at that moment the handler for hover doesn’t see the class on the element).

Changing the code can be done in two ways: either using the separate mouseover and mouseout (for example, in my original fiddle), or by passing two separate functions to the hover handler. When two functions are passed, the first is called when the mouse is over, and the second is called when the mouse is over.

 $(function () { var $Btn = $('.button'); $Btn.hover(function () { $(this).addClass("hover"); },function () { $(this).removeClass("hover"); }); /* first function is executed on mouseover, second on mouseout */ $Btn.on("click", function () { $(this).removeClass('hover'); // remove the hover class when button is clicked $('.move').toggleClass('angle'); }); }); 
 .move { border:1px solid #000000; padding: 10px; transition: transform .2s ease; /* have noticed issue is in "transition" */ } .button.hover { color: red; } .angle { transform: translate(100px, 0); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="move"> <button class="button">on click still red?</button> </div> 
+3
source share

All Articles