sticky icon indicating copy to clipboard operation
sticky copied to clipboard

Deactivate/block jquery.sticky.js on mobile devices

Open giuliamontes opened this issue 8 years ago • 5 comments

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

giuliamontes avatar Oct 16 '17 12:10 giuliamontes

@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();
      }

nersoh avatar Oct 19 '17 02:10 nersoh

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

giuliamontes avatar Oct 23 '17 15:10 giuliamontes

@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.

gustsu avatar Jan 16 '18 00:01 gustsu

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.

dannyfoo avatar Jan 25 '18 11:01 dannyfoo

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.

daco avatar Aug 30 '18 11:08 daco