2

I have a page where I want an image to appear after scrolling say 500px and I used the "If you want to show a div after scrolling a number of pixels, WITHOUT jquery" code snippet from apaul34208 (show div after 800px scroll). My adapted code is like this:

<!DOCTYPE html>
<html>
<body>

<div id="myID" class="pointer hide">
    <img src="image.png">
</div>

<script>
myID = document.getElementById("myID");

var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400) {
    myID.className = "pointer show"
} else {
    myID.className = "pointer hide"
}
};

window.addEventListener("scroll", myScrollFunc);

</script>
</body>
</html>

and CSS:

.hide {
   display: none;
}

.show {
   display: block;
   margin-top: -80px;
}

Only problem is that I would also like it to DISAPPEAR again lets say 400 px from the bottom of the page. the page-height differs from page to page so I cant just set a range like underneath from say 400-1000 px.

<script>
 myID = document.getElementById("myID");

var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400 & y <= 1000 ) {
myID.className = "pointer show"
} else {
    myID.className = "pointer hide"
}
};
window.addEventListener("scroll", myScrollFunc);

</script>
</body>
</html>

Anyone have any idea how I can make this happen?

Thanks guys!

Community
  • 1
  • 1
simenkl
  • 43
  • 2
  • 5

2 Answers2

4

$(document).ready(function() {
 $(window).scroll(function() {
        console.log('scrolling ', $(window).scrollTop(), $(document).height());
     if ($(window).scrollTop() >= 400 && $(window).scrollTop() <= ($(document).height() - 600)) {
         $('#myID').removeClass('hide');
        }
        else {
         $('#myID').addClass('hide');
        }
    });
});
.hide {
   display: none;
}
.body {
    height: 2000px;
}
#myID { 
    background-color: lightgray; 
    position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
    <div id="myID" class="pointer hide">
        STUFF HERE
    </div>
</div>
indubitablee
  • 8,136
  • 2
  • 25
  • 49
1

use document.height to get the height of the document and rest the desired value:

myID = document.getElementById("myID");
var myScrollFunc = function () {
    var y = window.scrollY;
    if (y >= 400 & y <= document.height - 400) {
        myID.className = "pointer show";
    } else {
        myID.className = "pointer hide";
    }
};
window.addEventListener("scroll", myScrollFunc);
taxicala
  • 21,408
  • 7
  • 37
  • 66