Search code examples
javascriptjquerycssmouseentermousehover

How to Toggle Mouse Hover Event on Click?


I want to change the color of element on Hover. However I want to disable hover effect while clicking on the element and set the clicked element red. Again if anyone clicks on the element , and I want to enable the Hover effect and apply the hover effect.

$('.divElement').on('mouseenter', function () {
    $(this).addClass('red');
});
$('.divElement').on('mouseleave', function () {
    $(this).removeClass('red');
});
$('.divElement').on('click', function () {
    $(this).removeClass('red');
    $(this).off('mouseenter mouseleave');
});

I Have tried this jQuery Code.

<div class="divElement">Element 1</div>
<div class="divElement">Element 2</div>
<span class="divElement">Element 3</div>
<div class="divElement">Element 4</div>

.divElement {
    color: blue;
}
.divElement.red {
    color: red;
}

Solution

  • What you have tried is just to disable (unbind) the Hover event. What You actually need is to toggle the hover event if it is clicked.

    First of all, I would like to suggest you, to change <span> tag to <div> or add CSS for class .divElemenT{ display:block;} else inline-block element and block element may hover at once.

    var hoverEvent= true;
    $(".divElement").hover(
      function() {
        if(hoverEvent) $(this).toggleClass("red");
      }
    );
    
    $('.divElement').click(function() {
       $(this).toggleClass('selected');
       $('.divElement').not(this).removeClass('selected,red');// remove this line if you want multiple selector
       hoverEvent= !hoverEvent;
    });
    .divElement {
        color: blue;
        display:block;
    }
    .divElement.red {
        color: red;
    }
    .selected{
    font-weight:bold;
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="divElement">Element 1</div>
    <div class="divElement">Element 2</div>
    <span class="divElement">Element 3</span>
    <div class="divElement">Element 4</div>

    Please leave a comment if it doesn't work.