views:

39

answers:

1

I can't seem to get preventDefault() to work with the following code... The browser still wants to jump to the top of the page after a click. Any ideas on how to fix this?

$('#controls a').click(function(event){

 event.preventDefault();

 var r = $(this).attr('rel');

 var c = $('#container').attr('class');
 // Prevent redundant actions
 if (r != c) {
  // Toggle 'active' class to show selection
  $('#controls a').removeClass('active');
  $(this).addClass('active');
  // Fade out function then callback to change the view mode
  $('#container').fadeOut(100, function(){    
     $('#container').removeAttr('class');
     $('#container').addClass(r);
     // Fade the container back in
     $('#container').fadeIn(100);
  });
 }

}); //end list view
+2  A: 

The problem (probably, this is partially a guess) isn't preventDefault(), but the fact yout page has less content for overall height for a moment (13ms to be exact), change your animation so it fades out but doesn't get the display: none; for a frame, like this:

$('#container').animate({ opacity: 0 }, 100, function(){    
  $('#container').removeAttr('class');
  $('#container').addClass(r);
  // Fade the container back in
  $('#container').animate({ opacity: 1 }, 100);
});

This way your #container is 0 height for a moment, causing the page to scroll back up simply because the page got shorter overall.

Nick Craver
oh shoot how did i miss that one you are correct just added min height to test that theory and it works you nailed it thanks
Terry
@Terry - does the above solution fix it for you?
Nick Craver
yes just updated it and indeed does work
Terry
@Terry - excellent :)
Nick Craver