0

I've been using thisJQuery code to fade in divs (all of the same class .showme)
But what I would like to do is fade out the previous div as the next one fades in.
Can anyone offer assistance on this?

    $(document).ready(function() {
       /* Every time the window is scrolled ... */
       $(window).scroll( function(){
         /* Check the location of each desired element */
         $('.showme').each( function(i){
           var middle_of_object = $(this).position().top + $(this).outerHeight() / 2;
           var middle_of_window = $(window).scrollTop() + $(window).height() /2;
           /* If the object is completely visible in the window, fade it it */
          if( middle_of_window >= middle_of_object ){
            $(this).animate({'opacity':'1'},2000);
          }
         }); 
       });
     });
3
Contributors
3
Replies
38
Views
2 Years
Discussion Span
Last Post by GlenRogers
0

Maybe a simple logic like this could resolve your problem:

    // $currentVisible will hold the current visible element 
    var $currentVisible = undefined;

    $(document).ready(function() {
       /* Every time the window is scrolled ... */
       $(window).scroll( function(){
         /* Check the location of each desired element */
         $('.showme').each( function(i){
             var $this = $(this),
                 middle_of_object = $this.position().top + $this.outerHeight() / 2,
                 middle_of_window = $(window).scrollTop() + $(window).height() /2;

           /* If the object is completely visible in the window, fade it in */
          if( middle_of_window >= middle_of_object ){

              /* If there is a visible element, fade it out */
              if ( $currentVisible !== undefined ) {
                  $currentVisible.animate({'opacity':'0'},2000);
              }

              $this.animate({'opacity':'1'},2000);
              /* Set the current visible as the  one being fade in*/
              $currentVisible = $this;
          }
         }); 
       });

       /* for the first scroll to work properly, you need to set the $currentVisible as the first div */
       $currentVisible = $("#myFirstDiv");

     });

Not tested ^^

0

does not work as expected on any display but yours

scrolling through a huge blank column on my laptop?? which just happens to be 1 pixel too short to display any div onscreen,

0

Ive used your code and it is fading out. But as every div is of the same class it alo fading out the one that has just faded in!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.