Reputation: 61
I want to add a jquery click event to href's that already have an onclick event. In the example below the hard coded onclick event will get triggered first. How can I reverse that?
<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>
Upvotes: 6
Views: 6235
Reputation: 31173
$(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);
});
});
});
});
Upvotes: 1
Reputation: 38400
You'll need to get the original event handler, replace it with your own and then call the original handler, however I'm not sure if that is possible with jQuery. Here is an example using jQuery only to access the element and then "normal" JavaScript to set 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);
}
})();
Upvotes: 6