user2004710
user2004710

Reputation: 187

Javascript scroll and window resize

I have a div class named navbar that I want to fadein when the page is scrolled 700px down. However, when the page width is less than 600px, I do not want it to show. Any ideas?

$(window).addEventListener('onresize',function(){ 
 $(window).scroll(function (e) {
 e.preventDefault();
  if ($(this).scrollTop() > 700 & window.innerWidth > 600) {
    $('.navbar').fadeIn();
  }
  else {
    $('.navbar').fadeOut();
  }
});
});

Upvotes: 1

Views: 5131

Answers (1)

xhg
xhg

Reputation: 1885

You do not need to add listener to "onresize", the window.innerWidth is dynamic so that it will varies on resize.

$(window).scroll(function (e) {
    e.preventDefault();
    if ($(this).scrollTop() > 700 && window.innerWidth > 600) {
        $('.navbar').fadeIn();
    }
    else {
        $('.navbar').fadeOut();
    }
});

or maybe you can separate into two in case you resize without scroll.

function listener (e) {
    e.preventDefault();
    if ($(window).scrollTop() > 700 && window.innerWidth > 600) {
        $('.navbar').fadeIn();
    }
    else {
        $('.navbar').fadeOut();
    }
}
$(window).scroll(listener);
$(window).resize(listener);

Upvotes: 2

Related Questions