简体   繁体   中英

Javascript for jumping to top and back on scroll

I have a function to let a container jump to the top upon scrolling 100px, and jump back in position once scrolled to the top again. I am working to disable this on smaller devices but the code I use also breaks the behaviour.

 $(window).scroll(function() {`
//After scrolling 100px from the top...
if ( $(window).scrollTop() >= 72 || w > 920 ) {
    $('#container').css('top', '0px');

//Otherwise remove inline styles and thereby revert to original stying
} else {
    $('#container').attr('style', '');

}
});

UPDATE: this code should actually make the container jump to the former position when you scroll to the top again. The problem is in 'w > 920'. I need that to disable the behaviour on smaller devices but it also breaks the function. I guess because of the 'AND' statement. The window width stays the same so possible because of that the revert breaks.

Not working fiddle

https://jsfiddle.net/xm1yq4to/

Working fiddle

https://jsfiddle.net/s15g7nup/

Is there another way to specify the devicewidth for this?

I ended up doing this in a different way bij not checking the device with but a change of class

$(document).ready(function() {
// run test on initial page load
checkSize();

// run test on resize of the window
$(window).resize(checkSize);
 });

//Function to the css rule
function checkSize(){
  if ($(".desktop-menu").css("display") == "block" ){
    $(window).scroll(function() {
      //After scrolling 100px from the top...
      if ( $(window).scrollTop() >= 100 ) {
        $('#container').css('top', '0px');
      } 
      //Otherwise remove inline styles and thereby revert to original stying
      else {
        $('#container').attr('style', '');
      }
    });
  }
return false;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM