Reputation:
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.
Upvotes: 0
Views: 3488
Reputation: 11297
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>
Upvotes: 0
Reputation: 13709
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!
Upvotes: 1