alexcuesta

My tech blog

JQuery: How to avoid scrolling when using fadeIn/fadeOut effects

with 9 comments

Today I had this problem at work using Jquery: I wanted to update the content of a div with the response from an ajax request in a nice way: first fading the div out and then fading it in. Something like this:

$("#mylink").click(function(){
	
  jQuery.ajax({
    type: "GET",
    url: "/my/url",
    success: function(msg){			  				
	         $("#content").fadeOut(200).empty().append(msg).fadeIn(200);				
            }
  });
					
  return false;
		
});	

But this doesn’t work nicely because the page scrolls up. Why? Because fadeOut sets the css property display to none.

I fixed it using fadeTo, like this:

$("#mylink").click(function(){
	
  jQuery.ajax({
    type: "GET",
    url: "/my/url",
    success: function(msg){			  				
               $("#content").fadeTo(200, 0, function () {
                    $("#content").empty().append(msg).fadeTo(200, 1);
                    });
		     }
  });
					
  return false;
		
});

Written by alexcuesta

October 14, 2009 at 10:13 am

Posted in HTML/Javascript

Tagged with

9 Responses

Subscribe to comments with RSS.

  1. Thanks!! you saved my dayđŸ˜€

    Adit

    January 27, 2010 at 3:21 pm

  2. Thanks !

    Quang

    February 11, 2010 at 3:18 am

  3. Thanks!!! Long time i look for that!

    LilScrappy94

    April 18, 2010 at 2:18 am

  4. Thank you!! I’ve been struggling with this issue for 2 hours..

    Nelson

    August 18, 2010 at 8:48 am

  5. Thanks man — exactly what I needed.

    Mike Nolan

    January 21, 2011 at 4:04 am

  6. thank you!!!

    cicciograsso

    June 6, 2011 at 9:53 am

  7. Thanks!

    Dan

    July 22, 2011 at 5:47 am

  8. Big Thanks!

    I was getting crazy!

    Carlitos

    August 5, 2011 at 7:56 am

  9. I have been trying to figure this out for the past 45 minutes! Thank you for solving this for me!!

    JT

    October 16, 2012 at 4:39 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: