views:

69

answers:

4

How do I catch all links and button pressed? Without having to add my JavaScript method to every link and button?

Anytime my browser wanrs to redirect to page1.aspx stop it from redirecting and have mt browser click a link found on the page to page2.aspx instead!

A: 

Whether or not this is a great idea, you can attack a listener to <body> since Javascript events bubble up the DOM tree unless you do otherwise. Here's how I'd do it with jQuery:

$('body').click(function (event)
{
    var $target = $(event.target);
    if ($target.is('a, :button'))
    {
        // your logic here
    }
});
Matt Ball
+3  A: 
            $(document).ready(function(){
              $("a,:button").click(function(){
               alert("Link or button clicked!");
              });
            });
Babiker
+1 for jQuery. It just make everything easier.
ckramer
+0 for not mentioning that it's JQuery
Mystere Man
works for link clicked, but button clicked it does not work!
K001
A: 

I think "Babiker's" solution is better than "Bears will eat you" because it calls the event handler only when link of button is clicked whereas in the other case, it calls for all the click events on the page and checks if the element clicked was a link or button.

Babiker's solution is more optimized.

Note, this wont work for any elements added in future.

You might wanna try this.

$("a, button").live("click", function(){ ... });
Ashit Vora
A: 
"<script type=""text/javascript"" src=""http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js""&gt;&lt;/script&gt;  

<script type=""text/javascript""> 
    $(document).ready(function(){
        $('body').click(function() {
           // do something here
        //alert(""Link or button clicked!"");
        });
    });
</script>"
K001