PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Click Once and Unbind

Click Once and Unbind

Have something happen on a click event, but only once! Unbind the click handler after the element has been clicked once.

$('#my-selector').bind('click', function() {
       $(this).unbind('click');
       alert('Clicked and unbound!');
});

Also see Ben's comment below for jQuery's .one() function which is essentially the same thing.

Subscribe to The Thread

  1. Doesn’t this have the same effect as:
    $(‘#my-selector’).one(‘click’, function() {
    alert(‘This can only happen once’);
    });

    ?

  2. Justin

    I need to re-bind a click event after some animate effects have been applied. What I want to happen is allow the user to click the button only once until the animate sequence has completed. In other words click (only allow once until event finishes), unbind, animate, re-bind click. I have had some trouble with this, any suggestions?

    • Instead of binding and unbinding the event, maybe instead just check if the element is animated before doing what you were going to do.

      You can test if something is currently being animated with :animated as part of the selector.

  3. Sweet! thanks guys.

    did not know the one() trick : -)

    art

  4. Hey,

    one() is a nice feature, but not always is a working solution. When we have a function, and inside we bind click event, to call that function recursively, we need to unbind the callback before we can call the function – if not, we get infinite loop.

    function f()
    {
    $('foo').click(function(){
    $(this).unbind('click');
    f();
    });

    // something else
    }

    We cannot do that with one() function. But thanks for the tips!

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~