garand / sticky

jQuery Plugin for Sticky Objects
Other
3.3k stars 1.06k forks source link

Deactivate/block jquery.sticky.js on mobile devices #265

Open giuliamontes opened 7 years ago

giuliamontes commented 7 years ago

I've a problem. I have to deactivate or block the fixed position of a sticky element on mobile devices to avoid the overlap of the fixed sidebar. The code is this:

$(function sticker(){ // document ready
   if ($('#sticker').length) { 
      var el = $('#sticker');
      var stickyTop = $('#sticker').offset().top; 
      var stickyHeight = $('#sticker').height();

      $(window).scroll(function(){ // scroll event

          var limit = $('#footer').offset().top - stickyHeight - 10;

          var windowTop = $(window).scrollTop(); // returns number

          if (stickyTop < windowTop){
             el.css({ position: 'fixed', top: 0 });
          }
          else {
             el.css('position','static');
          }

          if (limit < windowTop) {
          var diff = limit - windowTop;
          el.css({top: diff});
          }

        });

                             }
});
</script>

<script>
 function widthDetect(){ if (($(window).width() <= 768 )) { $("#sticker").unstick(); }
</script>

Suggestions? Thanks

nersoh commented 7 years ago

@giuliamontes I could handle sticky elements on mobile considering screen width size. I really didn't test your code, but I look at the example below to see if it helps you.

$(window).resize(function() {
        var windowWidth = $(window).width();

        if (windowWidth > 768) {
          stick();
        }
        else {
          unstick();
        }
      });

      function stick() {
        $("#sticker").sticky({
          topSpacing: 10,
          responsiveWidth: true
        });
      }

      function unstick() {
        $('#sticker').unstick();
      }
giuliamontes commented 7 years ago

@nersoh Hi, thanks. I tried but it doesn't work :( maybe my code is wrong

gustsu commented 6 years ago

@nersoh Your code works great for me. One important thing to note @giuliamontes is you still need to make sure and call the sticky function outside of window.resize. Otherwise you must resize the window before any of that code will run.

It would be nice if there was some build in support for this.

dannyfoo commented 6 years ago

I'm using this on Wordpress as below, but it only works after I hit refresh.

`jQuery(document).ready(function(){

$('header').sticky({ topSpacing: 0 });

if(window.innerWidth < 560)
{
    $('header').unstick();
}

});`

Not sure why this isn't firing from the beginning.

P.S. Not a programmer.

daco commented 6 years ago

Another option could be using

@media screen and (max-width: your-breakpoint)
.sticky-element {
     position: static !important;
}
}

in your css. This will override the inline position:fixed style.