osterello
osterello

Reputation: 21

jQuery run onclick function only once

How can I execute this function only one time? I tried .one but it doesn't work

$('a.inspire-tag').on('click',function () {         
    $('html, body').animate({
        scrollTop: $(".button-inspire").offset().top
    }, 400);
});

Upvotes: 2

Views: 2781

Answers (5)

Nephelococcygia
Nephelococcygia

Reputation: 1121

$('a.inspire-tag').on('click',doThis);
function doThis () {         
    $('html, body').animate({
        scrollTop: $(".button-inspire").offset().top
    }, 400);
    //you can off all on callback function
    $('a.inspire-tag').off('click',doThis);
}

Upvotes: 2

Leonardo Delfino
Leonardo Delfino

Reputation: 1498

If you want to do is just click once to enable

Try this:

$('a.inspire-tag').on('click',function () {         
    $('html, body').animate({
        scrollTop: $(".button-inspire").offset().top
    }, 400);
    $('a.inspire-tag').off('click');

});

Upvotes: 2

Use .off(), with name spaced event names

$('a.inspire-tag').on('click.myevent', function () {
    if (...)
    // remove current event handler
    $(this).off('click.myevent')
});

Upvotes: 1

Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

var inspiretag = $('a.inspire-tag');
inspiretag.on('click',function () {         
    $('html, body').animate({
        scrollTop: $(".button-inspire").offset().top
    }, 400);
inspiretag.off('click');
});

http://api.jquery.com/off/

Upvotes: 0

caramba
caramba

Reputation: 22480

var oneTime = true;
$('a.inspire-tag').on('click',function () {         
    if(oneTime) {
        $('html, body').animate({
           scrollTop: $(".button-inspire").offset().top
        }, 400);
        oneTime = false;
    }
});

Upvotes: 0

Related Questions