Change logo image on scroll down event (and change it back again on scroll up)

- 1 answer

Ad

I've got a logo image that I want to change on scroll event, I have this code that I've got but nothing is happening, what am I doing wrong?

This is the PHP/HTML:

<a class="logo" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="<?php echo esc_url( home_url( '/' ) ); ?>" data-fixed-height="<?php echo esc_attr( et_get_option( 'fixed_nav_logo_height', '51' ) ); ?>">
  <img src="<?php echo esc_attr( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo" />
</a>

This is the jQuery:

<script>

    ( document ).ready(function() {
    ('.ie #main-header #logo').attr('src','my_logo_image_url');

    (window).scroll( function () {
    ('body:not(.ie) #main-header #logo').not('.et-fixed-header').attr('src','my_logo_image_url');
    ('body:not(.ie) #main-header.et-fixed-header #logo').attr('src','my_alternative_logo_image_url');
    });
    });

</script>

Ad

Answer

Ad

Try this:

var lastTop = 0;
$(window).scroll( function (evt) {
  var thisTop = $(this).scrollTop();
  if (thisTop > lastTop) {
    // scroll down
    console.log('down');
  }
  else {
    // scroll up
    console.log('up');
  }
  lastTop = thisTop;
});

Where you see the console.log, place your image change code there. The reason for preserving the lastTop is that the user can continue to scroll down and you need to keep the image the same as the direction is the same.

Ad
source: stackoverflow.com
Ad