2

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);
});
4
  • 1
    .one() handler is executed at most once per element per event type. Do you have multiple elements 'a.inspire-tag' Commented Mar 6, 2014 at 19:22
  • 1
    What does "doesn't work" mean exactly ? Commented Mar 6, 2014 at 19:22
  • Have you tried $(this).off() inside your click function? Commented Mar 6, 2014 at 19:24
  • .one() seems to work fine for me - jsfiddle.net/tonicboy/F3E47 Commented Mar 6, 2014 at 19:26

5 Answers 5

2

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

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

Comments

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

1 Comment

You certainly want doThis without parens () when submitting it as a click handler, or the function will be invoked right on spot.
1

Use .off(), with name spaced event names

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

Comments

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

1 Comment

@carambly, yes this works, but we can use off or one also in Jquery
0
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.