Brandon Wang
Brandon Wang

Reputation: 3931

Stop events from triggering after they've been triggered once

I have the following code:

$('body').mousemove(function() {
    $('#covering').fadeOut(500);
    $('.block div div').fadeOut(250)
    $('.block div div').css('margin-top','160px')
    $('.block div div').fadeIn(250);
});

Basically what I am trying to do is have have a "covering" div fade out (as in this question) and have a few block elements' inner divs fade out, move silently, and fade back in for a seamless effect.

However, when this is run, every single time the mouse is moved, all of the above is run. It presents a problem as this is not what I want to happen (I want it to happen once, and that's it) and I am guessing it slows down the browser, possibly leading to a stackup.

I think I've read somewhere how to stop something from executing once it has executed once but I cannot remember it, so is there even a way to do this?

Upvotes: 1

Views: 258

Answers (2)

Nick Berardi
Nick Berardi

Reputation: 54854

Try the One Event. As stated it has the following function:

Binds a handler to one or more events to be executed once for each matched element.

I think this is what you are looking for, here is an example of the code, that you used above using the one event.

$('body').one("mousemove", function() {
    $('#covering').fadeOut(500);
    $('.block div div').fadeOut(250)
    $('.block div div').css('margin-top','160px')
    $('.block div div').fadeIn(250);
});

Upvotes: 1

James
James

Reputation: 111910

$('body').one('mousemove', function() {
        $('#covering').fadeOut(500);
        $('.block div div').fadeOut(250)
        $('.block div div').css('margin-top','160px')
        $('.block div div').fadeIn(250);
});

More info: http://docs.jquery.com/Events/one

Upvotes: 9

Related Questions