Use off()-method on mouseover() and mouseout()

3.3k views Asked by At

As my title shows I've problem using the off-method in JQuery combined with mouseover/mouseout.

My HTML-code(the relevant part):

 <h3>Hover</h3>
 <p id="hover">Move the mouse pointer over this paragraph.</p>
 <button id="off">Press the button</button>

My JQuery-code(the relevant part):

$(document).ready(function(){
    $("#hover").mouseover(function(){
         $("#hover").css("background-color", "green");
   });
   $("#hover").mouseout(function(){
        $("#hover").css("background-color", "lightblue");
   });
   $("#off").click(function(){
        $("#hover").off("click");
    });
});

The "hover-part" works fine. But when i press the button, which supposed to stop the mouseover and mouseout-methods to stop, it doesn't.

2

There are 2 answers

1
Saumya Rastogi On

You should use jQuery's unbind, to set off the event handlers like this:

$("#hover").unbind("mouseover mouseout");

$(document).ready(function(){
    $("#hover").mouseover(function(){
         $(this).css("background-color", "green");
   });
   $("#hover").mouseout(function(){
        $(this).css("background-color", "lightblue");
   });
   $("#off").click(function(){
        $("#hover").unbind("mouseover mouseout");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Hover</h3>
 <p id="hover">Move the mouse pointer over this paragraph.</p>
 <button id="off">Press the button</button>

Hope this helps!

0
Adam Azad On

The element has no click event listener added to, but mouseover and mouseout. Thus, no off() has no effect. Use:

$("#hover").off("mouseover mouseout");

$(document).ready(function(){
    $("#hover").mouseover(function(){
         $("#hover").css("background-color", "green");
   });
   $("#hover").mouseout(function(){
        $("#hover").css("background-color", "lightblue");
   });
   $("#off").click(function(){
        $("#hover").off("mouseover mouseout");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Hover</h3>
 <p id="hover">Move the mouse pointer over this paragraph.</p>
 <button id="off">Press the button</button>