Reputation: 55
I am developing a webpage and I wanted to know how to go about making animations based on where the page currently is.
What I mean is that : for example, the Markup below
<body>
<div id = "header">
<p> header content goes here</p>
</div>
<div id = "content">
<div id = "first">
<p>when I sroll into this region I want the background to darken up(and information appears) and an arrow to appear at the bottom showing prompting to scroll down</p>
</div>
<div id = "second">
<p>when I sroll into this region I want the navbar to to change appearace and display info relative to that div only </p>
</div>
<div id = "third">
<p>when I scroll into this region I want a another effect to occur</p>
</div>
</div>
<div id = "footer">
<p>footer content goes here</p>
</div>
</body>
if the web page loads and I scroll into each of the three divs in the then i want to have a defined effect in action. How do I do I go about that in JavaScript(Jquery)? or if anyone knows of any good sources where i can learn this technique i will love to know
Thank you all
Upvotes: 3
Views: 207
Reputation: 8787
Something like this should do the trick, either inside the pageLoad
or $(document).ready
methods:
var last,
docHeight= $(window).height(),
firstTop = $("#first").offset().top,
firstBottom = firstTop - docHeight,
secondTop = $("#second").offset().top,
secondBottom = secondTop - docHeight,
thirdTop = $("#third").offset().top,
thirdBottom = thirdTop - docHeight;
$(document).scroll(function(){
var thisTop = $(this).scrollTop();
if(thisTop <= thirdTop && thisTop >= thirdBottom){//#third is now visible
if(last != 3)//check if we're already in #third
console.log("entered third");//we entered #third for the first time, trigger effect
last = 3;
} else if (thisTop <= secondTop && thisTop >= secondBottom){
if(last != 2)
console.log("entered second");
last = 2;
} else if (thisTop <= firstTop && thisTop >= firstBottom){
if(last != 1)
console.log("entered first");
last = 1
} else
last = 0;
})
It attaches to the $(document).scroll
event, and using jquery's scrollTop()
for the document, and offset().top
of the elements, determines which one has been scrolled to. It also keeps a variable with the last element that was scrolled to, so the console.log
statements are only fired when the element is scrolled to originally, thus it won't fire while scrolling through the element.
Upvotes: 2
Reputation: 4769
I had a similar issue recently. I found the free and open-source divPeek library to be excellent.
https://github.com/davidhalford/DivPeek
No need to reinvent the wheel, especially if it has already been invented! :)
Upvotes: 1