views:

121

answers:

2

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>
+2  A: 

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);
  }
})();
RoToRa
A: 

UPDATED cause stackoverflow maitnance! ;-)

DEMO: http://jsbin.com/oxoja/5

just a proof of concept but you got the idea!

$(function() {
    $("a.whatever").removeAttr('onclick'); //remove onclick...
    $("a.whatever").click(function(e) {
        e.preventDefault(); //prevent clicked <a> jump around...
        var text = $(this).text(); // get text for sake...
        var cls = this.className.split(' ')[1].split('clickyGoal')[1];//get class
        $('p.goal' + cls).fadeOut(500, //little fadeout for sake...
        function() { //empty the <p> and insert new text...
            $(this).empty().append(text + ' button fired ' + cls).fadeIn(500,
            function() { //display alert...
                    alert(text);
            });
        });
    });
});

stripped to the bones:

$(function() {
    $("a.whatever").removeAttr('onclick'); //remove onclick...
    $("a.whatever").click(function(e) {
        var cls = this.className.split(' ')[1].split('clickyGoal')[1];//get class
        $('p.goal' + cls).html( $(this).text() ); 
        alert( $(this).text() );
    });
});
aSeptik