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.
You should use addEventListener() instead."
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
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.
Try this:
// Setting the DOM element's onclick to null removes // the inline click handler $("#sample")[0].onclick = null; $("#sample").click(function() { alert("done") });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With