Skilldrick
Skilldrick

Reputation: 70859

Can I remove inline event handlers using jQuery?

I have some HTML with an onclick attribute. I want to override that attribute using jQuery. Is there any way to remove the click handler using jQuery? Using unbind doesn't work.

Upvotes: 12

Views: 7061

Answers (5)

Abhay
Abhay

Reputation: 321

Tried given options but worked partially as they removed one but not all.

Instead I tried following chaining as workaround. I am using ver 1.4.2.

jQuery("selector")
    .removeAttr("onclick").removeAttr("onmouseout").removeAttr("onmouseover");

Upvotes: 0

Abhishek Sinha
Abhishek Sinha

Reputation: 5123

As quoted in http://api.jquery.com/prop/ Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 8, 9 and 11. To avoid potential problems, use .prop() instead.

So this can be done as

$(function() {
    $('a').prop('onclick', false);
});

Upvotes: 4

aikeru
aikeru

Reputation: 3983

There is a plugin for it, but you should only do this when you really need to. The plugin gives you the option to call the old function or to ignore it entirely.

jQuery Override Plugin

$(divElementObj).override('onclick', 'click', function(...));

Upvotes: 0

Tomalak
Tomalak

Reputation: 338228

$("#theElement")[0].onclick = function() {
  whatever();
};
// -- or --
$("#theElement")[0].onclick = null;

It's not that jQuery would make the standard DOM functions and properties go away. ;-)

Upvotes: 8

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

Try the .removeAttr() function:

$(function() {
    $('a').removeAttr('onclick');
});

jsfiddle demo.

Once you've got rid of the onclick attribute you could attach your own click handler.

Upvotes: 21

Related Questions