Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery delay a link from being followed

Tags:

jquery

I have a short css-based animation that I want to play out before a link is followed (a card that swooped in on page load swoops out after click). Currently, however, the page called loads too quickly. I want to be able to briefly delay the href from being followed.

Here's what I've got:

$(document).ready(function() {
    $("#card").css("top","0px");
    $(".clickit").click(function() {
        $("#card").css("top","-500");
    });
});

The first line swoops the card in on page load. After that is the click call that modifies the CSS, but like I said there needs to be some kind of delay in there because the page loads immediately, instead of after the animation. The CSS that is modified looks like this:

#card {
  width: 400px;
  height: 500px;
  position: relative;
  top: -500px;
  -webkit-transition:all .5s;
}

(yes, I know this is webkit-only right now)

This is a problem very similar to this question from 2008, but I know jQuery has been updated significantly since then, so I wanted to see if there was a more modern solution.

Thank you!

like image 594
Dan Sinker Avatar asked Jun 13 '10 12:06

Dan Sinker


2 Answers

Since you're using .css() and -webkit-transition:, you'll need to use a setTimeout() to delay the new location.

Try the live example: http://jsfiddle.net/2WJH9/

$(document).ready(function() {
    $("#card").css("top","0px");
    $(".clickit").click(function() {
        $("#card").css("top","-500px");  // Added px to make it work, 
                                         //   or get rid of quotes -500
        var href = $(this).attr('href');

             // Delay setting the location for one second
        setTimeout(function() {window.location = href}, 1000);
        return false;
    });
});​

The setTimeout() will delay the window.location from being set for 1 second (1,000 milliseconds). If you want to match the .5 seconds from -webkit-transition:, then change it to 500.

  • .setTimeout() - http://www.w3schools.com/js/js_timing.asp
like image 137
user113716 Avatar answered Sep 28 '22 07:09

user113716


You can preventDefault() on the link then use jQuery's animate function to perform your CSS transitions, following the link after the animation has completed.

$('.clickit').click(function(e) {
    e.preventDefault();
    href = $(this).attr('href');
    $('#card').animate( { top: '-500px' }, 500, function() {
        window.location = href;
    });
});
like image 23
ThrivingKings Avatar answered Sep 28 '22 07:09

ThrivingKings