I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.
On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page.
Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them. But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them.
Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked? Does it have to be some ugly javascript that catches every clicks and deal with them accordingly?
Thanks.
Yes. Instead of:
<a href="javascript:code">...</a>
Do this:
<a href="/non/ajax/display/page" id="thisLink">...</a>
And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class).
Here's the event handling and event-killer in jquery:
$("#thisLink").click(function(ev, ob) {
alert("thisLink was clicked");
ev.stopPropagation();
});
Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is so much cleaner than using onclick
attributes.
Yes, You need to lookup progressive enhancement and unobtrusive Javascript, and code your site to work with out Javascript enabled first and then add the Javascripts functions after you have the basic site working.
I liked Oli's approach, but it didn't discern from left and middle clicks. checking the "which" field on the eventArgs will let you know.
$(".detailLink").click(function (ev, ob) {
//ev.which == 1 == left
//ev.which == 2 == middle
if (ev.which == 1) {
//do ajaxy stuff
return false; //tells browser to stop processing the event
}
//else just let it go on its merry way and open the new tab.
});
It would require some testing, but I believe that most browsers do not execute the click handler when you click them, meaning that only the link is utilized.
Not however that your handler function needs to return false to ensure these links aren't used when normally clicking.
EDIT: Felt this could use an example:
<a href="/Whatever/Wherever.htm" onclick="handler(); return false;" />
<a href="/original/url" onclick="return !doSomething();">link text</a>
For more info and detailed explanation view my answer in another post.
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