views:

74

answers:

4

$('#start') executes the function myFunction() and $('#stop') end it. How do I stop myFunction() from executing?


function myFunction() {
     $(document).mousemove(function(e) {
          $('#field').html(e.pageY)
     });
}


$('#start').click(function() {
    myFunction();
});


$('#stop').click(function() {
   //stop myFunction
});
+2  A: 

You're not stopping the function from executing. Your myFunction() simply attaches a callback to an event listener, which is called whenever the mouse is moved on the document. The callback function is invoked and is terminated immediately.

You'd simply want to unbind the callback from the event listener. Check out the other answers for concrete examples.

Daniel Vassallo
its not stopping it from executing.
dany
+2  A: 

A better way would be to use bind and unbind, like so:

function myFunction() {
     $(document).mousemove(function(e) {
          $('#field').html(e.pageY)
     });
}

$('#start').bind('click', myFunction);

$('#stop').click(function() {
   $('#start').unbind('click', myFunction);
});
Liam Bailey
@Liam Bailey, great. Thank you very much!
dany
It should be `bind('click', myFunction)`, not `bind('click', myFunction())`. Similar for `unbind`.
KennyTM
Thanks KennyTM, I have never actually used jQuery's binding capabilities with named functions.
Liam Bailey
@KennyTM, thank you for the fix
dany
+3  A: 

As Daniel pointed out, you actually want to unbind the event handler. You can use unbind for this:

$('#stop').click(function() {
    $(document).unbind('mousemove');
});

But this will also remove all other mousemove event handlers, that might be attached by other plugins or similar (I mean, you attach to the document element not a "custom" element, so it can be that other JavaScript code also binds handlers to this element).

To prevent this, you can use event namespaces. You would attach the listener with:

function myFunction() {
     $(document).bind('mousemove.namespace', function(e) {
          $('#field').html(e.pageY);
     });
}

and unbind:

$('#stop').click(function() {
    $(document).unbind('mousemove.namespace');
});

This would only remove your specific handler.

Felix Kling
@Felix Kling, this is more practical. Thank you!
dany
+2  A: 

You want to use the jQuery bind and unbind methods. For example:

function myFunction() {
     $(document).mousemove(function(e) {
          $('#field').html(e.pageY)
     });
}


$('#start').bind('click.myFunction', function() {
    myFunction();
});

$('#stop').bind('click', function() {
    $('#start').unbind('click.myFunction');
});
Blair McMillan
@Blair McMillan, thanks!!
dany
No worries. The second half of Felix's answer is even better.
Blair McMillan