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);
          }
         }); 
       });
     });

Recommended Answers

All 3 Replies

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 ^^

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,

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.