001
001

Reputation: 65205

How to catch link or button click?

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!

Upvotes: 1

Views: 820

Answers (3)

001
001

Reputation: 65205

"<script type=""text/javascript"" src=""http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js""></script>  

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

Upvotes: 0

Ashit Vora
Ashit Vora

Reputation: 2922

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(){ ... });

Upvotes: 0

Babiker
Babiker

Reputation: 18818

            $(document).ready(function(){
              $("a,:button").click(function(){
               alert("Link or button clicked!");
              });
            });

Upvotes: 4

Related Questions