Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery event handlers stacking

i have something like this: http://jsfiddle.net/PTcw8/4/

<div id="container">
    <a href="#" onclick="javascript:alert('inline'); return false;"> show me </a>
    <br />
    <input type="button" value="click to change the links onclick event" onclick="javascript:changeOnClick(); return false;" />
</div>​

function changeOnClick() {
    $("#container a").unbind('click');
    $("#container a").on('click', function() {
        alert("changed on the fly");
    })
}​

the link has an inline onclick event, i cant unbind it and bind a new handler, they just stack for some reason.

isn't it possible to unbind inline handlers?

like image 893
Farzad Bekran Avatar asked Jan 29 '26 11:01

Farzad Bekran


2 Answers

You can only .unbind() an event handler if you have previously attached it with .bind():

Event handlers attached with .bind() can be removed with .unbind().

For inline event handlers, either use:

$("#container a").removeAttr("onclick");

or

$("#container a")[0].onclick = null;

DEMO.

like image 179
João Silva Avatar answered Jan 31 '26 00:01

João Silva


I would do this:

$(document).ready(
    function(){
       $("#container a").removeAttr("onclick");
       $("#container a").on('click', function() {
          alert("changed on the fly");
       })
    }
);
like image 25
Matt Cashatt Avatar answered Jan 31 '26 01:01

Matt Cashatt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!