Sean Adkinson
Sean Adkinson

Reputation: 8605

Global Javascript link handler

Here's what I have:

What I want is to be able to catch link clicks whose destination is myapp.req?id=123, and instead of reloading the page, just open the tab for item 123, leaving anything else currently loaded alone. If the link is for an external website, though, obviously just let the browser leave.

So my question really: Can I have a global link handler that checks if I want to handle the link click, and if so, run some Javascript and don't leave?

I understand I could find all <a>s and add listeners, but my hope is that the solution would only require setting up the listener once, and not adding link handlers every time new content is loaded on the page. Since content can be loaded many different ways, it would be cumbersome to add code to all those places.

Does that make sense?

Upvotes: 2

Views: 2258

Answers (3)

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110922

Sure you can. Add a clickhandler on the body. So you catch all clicks. Then you have to check if the target of the event or one of its parent is a link with your specific href. In this case stop the event and open the tab.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

updated to use .live instead of .click

If you use jQuery, you can add a "live" click event handler to every a href at once:

<body>
    <a href="app.req?id=123&test=432">click here</a>
    <br/>
    <a href="http://whatever.com">whatever</a>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript"> 
$('a').live('click',function() {
    var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
    if (myID) {
        //run code here
        alert(myID);
        return false;
    }
});
</script>

This should extract the id from the href's query string and let you do whatever you want with it.

Upvotes: 0

Joe
Joe

Reputation: 82594

jQuery's live is what you need:

$('a').live("click", function () {
    var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
    if (myID) {
        //run code here
        alert(myID);
        return false;
    }
});

Any link will now have this click handler whether it's been added after this is called or not.

Upvotes: 2

Related Questions