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>
That is: for a click on <td> the event first goes through the ancestors chain down to the element (capturing phase), then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way.
The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more.
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.
The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.
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);
}
})();
- DEMO: http://so.devilmaycode.it/order-of-onclick-events
$(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);
});
});
});
});
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