views:

3474

answers:

2

Hi. I'm trying to add a transition to a site where the page fades to black when a user navigates through the site. Here's an example of what I have so far.

I decided the best way to achieve this was to create a div which will mask the page in blackness and then animate it with jQuery.

So far I've managed to create the code for the "fade to black" effect...

$(document).ready(function(){
    // Insert mask after container
    $('.container').after('<div class="mask"></div>');
    // Delay the fadeOut effect for half a second so you can actually see it
    $('.mask').animate({opacity: 1.0}, 500)
    // Slowly make the mask dissapear
    .fadeOut('slow');
});

But I'm not sure how to get the page to "fade from black" when the user clicks another part of the site.

I understand I would have to use the click function, but how would I delay the page from loading in time to be able to see the "fade to black" animation?

Many thanks for your time.

+3  A: 

You can bind to the click() event and make it return false, thus preventing the default action (the page going to the link's href). You can then bind a callback to the fadeIn() method that sets the document's location to the link's hypertext reference.

You could do something like this:

$('a').click(function(){
  var url = $(this).attr('href');

  $('.mask').fadeIn('slow', function(){
    document.location.href = url;
  });

  return false;
});

Thanks! Jamie

Jamie Rumbelow
+1  A: 

Capture the click event and prevent the default behavior from happening:

$('a').click(function(event) {
  event.preventDefault();

  // mask effect code here
});

The event.preventDefault() is akin to using a onclick='function(); return false;' in non-jQuery JavaScript.

Hooray Im Helping
No need to pass the event object or call preventDefault() - jQuery listens for the return value, and if false, it disables the event automatically.
Jamie Rumbelow
I wasn't aware of that, but I still prefer to use event.preventDefault() for clarity.
Hooray Im Helping