steo
steo

Reputation: 4656

How to bind an event only after it loses binding before

I have a div on which I bound click like this:

  $("#mydiv").one('click',function(){ ... });

Because I want to execute an action only one time. Now I wanto to re-bind it

  $("#mydiv").on('click',function(){ ... });

But only if the users clicked on it , at least the first time.

How can I do that?

Upvotes: 1

Views: 64

Answers (2)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

$('#mydiv').one('click', function() {
    // ...
    // code here for action-A, on first click
    // ...
    $(this).on('click', function() {
        // ...
        // code here for action-B, on subsequent clicks
        // ...
    });
});

Upvotes: 1

Vinay
Vinay

Reputation: 6322

You can namespace events with jQuery:

$('#mydiv').on('click.firstClick', function () {
    // do stuff for the first time
    $(this).off('click.firstClick'); // only removes this event
});

$('#mydiv').on('click', function () {
    // stuff that always happens when you click
});

If you simply want to have something happen the first time and then something happen every time after that:

$('#mydiv').click(function () {
    // stuff that happens the first time you click
    $(this).off('click');
    $(this).click(function () {
        // stuff that happens every time after this
    });
});

Example of first scenario: http://jsfiddle.net/75HWV/ Example of second scenario: http://jsfiddle.net/SbhY3/

Upvotes: 6

Related Questions