Onclick event order

I want to add a jquery click event for href that already has an onclick event. In the example below, the hardcoded onclick event will be fired first. How can i cancel this?

<a class="whatever clickyGoal1" href="#" onclick="alert('trial game');">play trial</a> <br /> <a class="whatever clickyGoal2" href="#" onclick="alert('real game');">real trial</a> <p class="goal1"> </p> <p class="goal2"> </p> <script type="text/javascript"> $("a.clickyGoal1").click(function() { $("p.goal1").append("trial button click goal is fired");//example }); $("a.clickyGoal2").click(function() { $("p.goal2").append("real button click goal is fired"); //example }); </script> 
+6
jquery events order onclick
source share
2 answers

You will need to get the original event handler, replace it with your own, and then call the original handler, however I'm not sure if this is possible using jQuery. Here is an example of using jQuery to access an element only, and then using β€œnormal” JavaScript to install the handler:

 // Wrapper in order not to add unnecceary variables to the global namespace (function (){ var link = $("a.clickyGoal1")[0]; var oldOnClick = link.onclick; link.onclick = function(e) { $("p.goal1").append("trial button click goal is fired"); oldOnClick(e); } })(); 
+6
source share
  $(function() { $("a.whatever").removeAttr('onclick').click(function(e) { e.preventDefault(); var text = $(this).text(); var cls = this.className.split(' ')[1].split('clickyGoal')[1]; $('p.goal' + cls).fadeOut(500,function() { $(this).html(text+' button fired '+cls).fadeIn(500,function() { alert(text); }); }); }); }); 
+1
source share

All Articles