0

I have a fixed div that I have placed to the right: -35px. I want it to come right: 0px once one scrolls past 350px. I have the jquery code below

$(window).scroll(function() {
var height = $(window).scrollTop();

if(height  > 350) {
     $("#MySideDiv").animate({ "right": 0 }, "slow")
     }
else{
     $("#MySideDiv").animate({ "right": -55 }, "slow")
     }
 });

This only works well when I don't include the else bit. Yet I want it to disappear if the user scrolls back to less then 350px. Is there a way to achieve this?

BiKe
  • 83
  • 1
  • 12
  • So, in what way does it not work well, when including `else`? – Geshode Dec 20 '18 at 09:28
  • try adding a `.stop()` before the animate - `.stop().animate({...})`, otherwise you could try firing it [on scroll end](https://stackoverflow.com/questions/9144560/jquery-scroll-detect-when-user-stops-scrolling) – Pete Dec 20 '18 at 09:38

1 Answers1

1

I'm not sure I understand your problem exactly but I hope this can help.

var isVisible = false;
$(window).scroll(function() {
var height = $(window).scrollTop();
var div = $("#MySideDiv");

  if(height  > 350 && isVisible === false) {
        div.clearQueue().stop().animate({ "right": 0 }, 'slow');
      isVisible = true;
   } else if (height  < 350 && isVisible === true) {
      div.clearQueue().stop().animate({ "right": '-55px' }, "slow");
      isVisible = false;
     }
 });

https://jsfiddle.net/mfbgqxyp/1/

akcoban
  • 953
  • 7
  • 14
  • Thanks a lot, this solved the issue. I think I'll have to read mor on .stop() and etc – BiKe Dec 20 '18 at 14:51