Dan Sinker
Dan Sinker

Reputation: 3623

jquery delay a link from being followed

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!

Upvotes: 6

Views: 18483

Answers (3)

ThrivingKings
ThrivingKings

Reputation: 73

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;
    });
});

Upvotes: 5

user113716
user113716

Reputation: 322492

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.

Upvotes: 11

T.J. Crowder
T.J. Crowder

Reputation: 1074365

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.

Nope, still the same answer. Cancel the event, then load the location yourself later.

Upvotes: 2

Related Questions