Search code examples
jqueryif-statementscrollresponsiveness

jQuery Change Image on Scroll at Responsive Breakpoint


I have a script working fine that changes an image / logo on scroll, but I only want this to fire if the browser window is more than 767px - otherwise nothing/keep 'as is'. How can I modify this script to achieve that please:-

 jQuery(function($) {
//caches a jQuery object containing the brand image element
var brandimg = $(".x-brand img");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
 // if( $(window).width() > 767 {
  if (scroll >= 40) {
        brandimg.attr('src', 'logo-icon.png');
        brandimg.removeClass('x-img-1').addClass("img-2");
    } else {
      brandimg.attr('src', 'logo-full.png').addClass("logo-full");
      brandimg.removeClass("x-img-2").addClass('img-1');
    }
});
});

I can't use a media query here as the 'Wordpress' theme uses an image rather than image background.

Not sure perhaps an additional if statement surround the current function?

Thanks

Glennyboy


Solution

  • This is how I did it in the end:-

    jQuery(function($) {
    //caches a jQuery object containing the brand image element
    var brandimg = $(".x-brand img");
    jQuery(window).on("focus load resize scroll",function(e){
    var scroll = $(window).scrollTop();
    if (($(window).width() < 460) || (scroll >= 40)) {
            brandimg.attr('src', 'logo-icon.png');
            brandimg.removeClass('x-img-1').addClass("x-img-2");
        } else {
          brandimg.attr('src', 'logo-full.png').addClass("logo-full");
          brandimg.removeClass("x-img-2").addClass('x-img-1');
        }
    });
    });
    

    And it works perfectly for scroll and window size on load, resize and scroll