Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fade a div in/out on page scroll?

Here is the jsfiddle: http://jsfiddle.net/NKgG9/

I'm basically wanting those pink boxes to be on show on page load as normal but as soon as a user scrolls down the page I want them to fade out and disappear. When the user scrolls back up to their position or the top of the browser window I want those pink boxes to fade back in again. I'm useless with JS so good do with some help on how to do this.

All help appreciated.

like image 807
egr103 Avatar asked Feb 24 '12 22:02

egr103


People also ask

How do I fade a div in JavaScript?

jQuery Effect fadeOut() Method The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeIn() method.

What is fade out effect?

The Fade In/Fade Out behavior lets you dissolve into and out of any object by ramping the opacity of the object from 0 percent to 100 percent at the start, and then back to 0 percent at the end. You can eliminate the fade-in or fade-out effect by setting the duration of the Fade In Time or Fade Out Time to 0 frames.


2 Answers

Very simple example: http://jsfiddle.net/a4FM9/2/

var divs = $('.social, .title');
$(window).scroll(function(){
   if($(window).scrollTop() <10 ){
         divs.stop(true,true).fadeIn("fast");
   } else {
         divs.stop(true,true).fadeOut("fast");
   }
});​
like image 102
Cheery Avatar answered Sep 24 '22 07:09

Cheery


Like this? http://jsfiddle.net/NKgG9/6/

$(function(){ 
    var targets = $(".title, .social");
    if($(window).scrollTop() > 10){
      targets.hide();
    }
    $(window).scroll(function(){
        var pos = $(window).scrollTop();
        if(pos > 10){
            targets.stop(true, true).fadeOut("fast" );
        } else {
            targets.stop(true, true).fadeIn("fast");
        }
    });

});

The basic idea: subscribe to the scroll event. If the scroll position moves past a certain point, start the fade out and likewise if the user scrolls up fade in. Some important details: keep track if you're already fading in/out (variable shown) and stop any ongoing fade if you start a new fade.

like image 27
Andre Loker Avatar answered Sep 23 '22 07:09

Andre Loker