views:

168

answers:

3

This seems deceptively simple.

How do you override the onclick event in the following HTML using JavaScript?

<a id="sample" href="..." onclick="alert('hello world')" />...</a>

I've tried it with jQuery, but that didn't do the trick:

$('#sample').attr('onclick','alert("done")')

Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.

A: 

try:

document.getElementById("sample").onclick = $.noop;

$.noop == function(){};

jQuerty noop

David Murdoch
This didn't work either.
Diodeus
`$("#sample")[0].onclick = null;` and `document.getElementById("sample").onclick = $.noop;` are nearly identical. how can you say that this did not work?
David Murdoch
+2  A: 
<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>

Or

$('#sample').attr('onclick','alert("done"); return false;')

Despite being able to set the return false; either directly in the onclick or by using jQuery, it doesn't actually require jQuery to be used at all. The benefit is if for whatever reason your jQuery script leads to a 404, your code will still work.

I found the answer here.

ILMV
+1 This is better than the answer I gave. :-)
David Murdoch
Return false is not the problem, and this doesn't work.
Diodeus
Oh balls, I think I've completely misunderstood your question! Sorry dude :S
ILMV
+2  A: 

Try this:

// Setting the DOM element's onclick to null removes 
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });
Andrew Hare
That was non-obvious, and it worked. Thanks Andrew. Why the [0]?
Diodeus
@Diodeus: jQuery objects, much like DOM collections or arrays, have numerical indexes for each contained element. `[0]` will fetch the first matched element of the selector.
Andy E
I would assume since I'm selecting by ID that it would be unique and never result in an array. Sometimes what seems logical is....wrong.
Diodeus
@Diodeus - Andy is correct @Andy Thanks!
Andrew Hare
+1, I completely misunderstood the question... whoops :D
ILMV