Home > JQuery, Javascript > Delayed Link Opening

Delayed Link Opening

November 16th, 2009 kaheidt Leave a comment Go to comments

Depending on the type of animations and actions you have in your site, you might be interested in having an anchor link perform some kind of animation that finishes before opening the link in the href attribute. For example, I’m currently working on a site that has a colored box behind the navigation link of the current page. Then when another link in the navigation is clicked, the colored box slides to be behind that link. So I wouldn’t want the url for that second navigation link to open until the colored box is done moving. I’ll cover two ways to do this.

The first method is the validation method. You’ll see this a lot with forms, where a validation function must be returned as true in order for a form to be submitted. If it’s returned false, then the form won’t be submitted. This will also work for anchor tags, and is all made possible by the two event models. Here’s an example of the javascript code that would be called.

< script src=”http:/ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js” type=”text/javascript”>< /script>
< script type=”text/javascript”>
function validate(field){
$(field).animate({“top”:”100px”}, 1000,”",function(){
if ($(field).attr(“target”)==”_blank”){
window.open($(field).attr(“href”));
}else{
location.href=$(field).attr(“href”);
}
});
return false;
}< /script>

And here’s the anchor html code that would be used:

< a id="link1" class="link" onclick="return validate(link1)" name="link1" href="http://www.google.com/" target="_blank">Google< / a>

The second method is very similar, except we don’t need to use inline javascript event handling, which is nice for dynamic page management. So here’s what the javascript would look like:

< script src="http:/ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript">< /script>
< script type="text/javascript">
$(document).ready(function(){
$(".link").live("click",function(event){
event.preventDefault();
$(this).animate({"top":"100px"}, 1000,"",function(){
if ($(this).attr("target")=="_blank"){
window.open($(this).attr("href"));
}else{
location.href=$(this).attr("href");
}
});
});
});
< /script>

And here’s what the anchor HTML code would look like:

< a class="link" href="http://www.google.com/" target="_blank">Google< / a>

You can see how it would be much easier to not have to maintain unique IDs for each link that you want to open. The “live” function of JQuery takes care of every anchor that has a class of “link” applied to it. The other nice thing about this is that if you click the link with your middle mouse button to force it to open into a new page or tab, it will do so right away without waiting for animations or anything.

Categories: JQuery, Javascript Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.
Contact Form Powered By : XYZScripts.com