2

If I have a .click() function in the header of my page, is it possible to overwrite it later in the page?

For example if I have this in the header:

<script>
$("document").ready(function() {
    $("a.lol").click(function () { 
        alert("aaa");
    });
});
</script>

Would it be possible to change $("a.lol") to alert something else, and not alert "aaa"?

5 Answers 5

5

Try this,

$("document").ready(function() {
    $("a.lol").click(function () { // initially the click event
        alert("aaa");
    });
    $("a.lol").off('click');// off the click event
    $("a.lol").on('click',function () { // again bind new click event with on()
        alert("new click");
    });
});

Read on() and off()

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

3 Comments

It's my understanding that off() will not remove a handler added with click(). From the docs: "The .off() method removes event handlers that were attached with .on()."
@BrianStephens I just tried it. Works fine for me. If you look at the source code you'll see that .click simply maps to .on internally (as do .bind and .delegate).
@Blazemonger Good to know! I was never sure if I was interpreting the documentation right. Thanks.
3

You can use .unbind() and then "put it back" adding a new handler.

$("a.lol").unbind('click');

Comments

1

Use .off()

$("a.lol").off('click');

and to add back use .on()

$("a.lol").on('click',functionName);

or

$("a.lol").on('click',function () { 
    //code here
});

Comments

0

Use $("a.lol").off('click') to remove all click handlers. Afterwards, you can install new ones.

For older versions of jQuery, use unbind()

Comments

0

Yes, you will have to remove the current handler with off() and then call click() again with the new handler.

// Some code
$("a.lol").off("click")
$("a.lol").click(function () { 
    alert("ooo");
});

PS: Depending on your use case you could maybe use one() which would trigger the handler only once and then remove itself

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.