Skip to content
Advertisement

How do I make a jQuery click event revert to what it otherwise would’ve been?

I have a click event

        $('[data-assetid]').click(function(){
            $.ajax({
                url : '/somemethod',
                method : 'POST',
                data : { pageid : $('input[name="pageid"]').val() },
                success : function ( retobj ) {
                    // ... 
                }
            });
            
        });

that is on elements that by default have click events (<img>s, <a>s, etc.). What I want it to do at the end of the success callback is remove the click event I had attached in the first place, so that it falls back to what it otherwise would’ve been. How do I do this?

Advertisement

Answer

You can use jQuery.one (check API); it will bind it once and then unbind after the first call.

Like this:

    $('[data-assetid]').one("click", function(){
        $.ajax({
            url : '/somemethod',
            method : 'POST',
            data : { pageid : $('input[name="pageid"]').val() },
            success : function ( retobj ) {
                // ... 
            }
        });

    });
Advertisement