Fernando Souza Fernando Souza - 4 months ago 14
Javascript Question

Fade in and out when scrolling with jquery

I want to show a div every time an amount of pixels are scrolled, and fade it out after some more scrolling. I found out some logic but, there is a conflict in the end,the div is fading in again, as I am telling every time scroll is > 250 it will fade in.
How can I solve it?

$('#1').hide();

$(window).scroll(function() {
if ($(this).scrollTop() > 250) { //use `this`, not `document`
$('#1').fadeIn();
}
if ($(this).scrollTop() > 1250) { //use `this`, not `document`
$('#1').fadeOut();
}
});

Answer

Show the element only if scrollTop value is less than or equal to 1250.

if ($(this).scrollTop() > 250 && $(this).scrollTop() <= 1250){
   $('#1').fadeIn();
} 

Although you can use stop() to stop the previous animation.

$(window).scroll(function() {
  if ($(this).scrollTop() > 250) {
    if ($(this).scrollTop() > 1250) 
       $('#1').stop().fadeOut();
    else
       $('#1').stop().fadeIn();
  }
});  
Comments