Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you override inline onclick event?

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.

like image 795
Diodeus - James MacFarlane Avatar asked Apr 13 '10 13:04

Diodeus - James MacFarlane


People also ask

What is alternative for onclick?

You should use addEventListener() instead."

Can you have two onclick events HTML?

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

Why Onclick works only once?

onclick event works only once in arctext script. Here is the code in Codepen: http://s.codepen.io/Noureddine/debug/JbbBQX. Well you only execute the random part once. If you want it to execute again, you need to move that logic inside.


1 Answers

Try this:

// Setting the DOM element's onclick to null removes  // the inline click handler $("#sample")[0].onclick = null; $("#sample").click(function() { alert("done") }); 
like image 81
Andrew Hare Avatar answered Sep 20 '22 21:09

Andrew Hare