0

$('#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 }); 

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this is more practical. Thank you!
2

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'); }); 

1 Comment

No worries. The second half of Felix's answer is even better.
2

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.

1 Comment

its not stopping it from executing.
2

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); }); 

2 Comments

It should be bind('click', myFunction), not bind('click', myFunction()). Similar for unbind.
Thanks KennyTM, I have never actually used jQuery's binding capabilities with named functions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.