Reputation: 1
I've got a page made of several sections (think a classic parralax setup). Now that I have it all built I want to start making certain parts do cool things when I scroll to them.
In my ignorance I assume that means I'll need to get the offset().top for each position and compare it to the window's scrollTop().
Here is what I have going on, as an example:
$(window).scroll(function(){
var scrollPosition = $(this).scrollTop();
var sectionFourPosition = $('.slideFour').offset().top;
var sectionFourFlag = 0;
if( sectionFourFlag == 0 && scrollPosition >= sectionFourPosition ){
alert("You Passed the Top of Section Four");
sectionFourFlag++;
};
$('.ScrollPositionDisplay').text(scrollPosition);
$('.SectionFourOffsetDisplay').text(sectionFourPosition);
$('.SectionFourFlagDisplay').text(sectionFourFlag);
});
I've got a little panel I use to show me the state of various variables in my project. I have the sectionFourFlag there as I only want this to execute the one time. I figure I can then flip the flag to 1 and that should break the IF statement...
No such luck. It keeps running despite the Flag showing as one. So for every incirment I scroll past the "sectionFourPosition", the alert goes of again, and again, and again...
This SEEMS like it should work, and my GoogleFu has failed me.
What have I left out?
Upvotes: 0
Views: 43
Reputation: 6120
You did good, with one error:
$(window).scroll(function(){
var scrollPosition = $(this).scrollTop();
var sectionFourPosition = $('.slideFour').offset().top;
var sectionFourFlag = 0;
if( sectionFourFlag == 0 && scrollPosition >= sectionFourPosition ){
alert("You Passed the Top of Section Four");
sectionFourFlag++;
};
$('.ScrollPositionDisplay').text(scrollPosition);
$('.SectionFourOffsetDisplay').text(sectionFourPosition);
$('.SectionFourFlagDisplay').text(sectionFourFlag);
});
You are resetting your sectionFourFlag
every time you scroll. You should put the var sectionFourFlag = 0;
outside the scroll function, like:
var sectionFourFlag = 0;
$(window).scroll(function(){
var scrollPosition = $(this).scrollTop();
var sectionFourPosition = $('.slideFour').offset().top;
if( sectionFourFlag == 0 && scrollPosition >= sectionFourPosition ){
alert("You Passed the Top of Section Four");
sectionFourFlag++;
};
$('.ScrollPositionDisplay').text(scrollPosition);
$('.SectionFourOffsetDisplay').text(sectionFourPosition);
$('.SectionFourFlagDisplay').text(sectionFourFlag);
});
Upvotes: 1
Reputation: 7401
This is your issue:
var sectionFourFlag = 0;
if( sectionFourFlag == 0 && scrollPosition >= sectionFourPosition ){
The part sectionFourFlag == 0
can never be false while you define sectionFourFlag
within your JavaScript; you need to initialise it outside of this procedure.
Upvotes: 0