Johan Fredrik Varen
Johan Fredrik Varen

Reputation: 3914

How do I animate a clicked link before leaving page?

Here's what I want to achieve:

  1. When an HTML link is clicked, I want to animate it before leaving the page
  2. If the link is opened in a new window/tab, the animation should not take place

How on earth do I achieve this?

Upvotes: 1

Views: 3856

Answers (2)

Jon Abrams
Jon Abrams

Reputation: 2171

You'll need to capture the click event, prevent the default action, do the animation, then load the new page.

If using jquery (Available as a jsfiddle):

$('a').click(function (event) {
  event.preventDefault();
  $(this).animate({
    //whatever
  }, function() {
    location.href = $(this).attr("href");
  });
});

Update: Here's the new jsfiddle that accounts for the situation mentioned in the comments, go there for the updated code. The trick is to look for the keypress of ctrl or command, and abort the newly defined animated click handler if either key is pressed.

Note: The window needs focus before it can detect a keypress, in jsfiddle, that means the frame needs focus before it'll work.

Upvotes: 0

Justin Case
Justin Case

Reputation: 124

You could use javascript

$(function(){
  $(".btn").bind("click",function(){
    $(this).animate({'left': '100px'}, 100, function(){
    window.location.href = index.html
  })
 })
})

But you'll have to stop the default action if your button is a link.

Upvotes: 2

Related Questions