So I am definitely a beginner at js, and this is probably simple but I don't know why this isn't working. I am trying to get a div to appear when the page Y Offset is greater than 30, but it isn't working.
//js is below
var x = document.getElementById('play');
var ypos = window.pageYOffset;
var see = function() {
if (ypos > 30) {
x.style.opacity = 1;
} else {
console.log('not working');
}
}
window.addEventListener("scroll", see);
So I am definitely a beginner at js, and this is probably simple but I don't know why this isn't working. I am trying to get a div to appear when the page Y Offset is greater than 30, but it isn't working.
//js is below
var x = document.getElementById('play');
var ypos = window.pageYOffset;
var see = function() {
if (ypos > 30) {
x.style.opacity = 1;
} else {
console.log('not working');
}
}
window.addEventListener("scroll", see);
Share
Improve this question
asked Jan 26, 2015 at 3:27
BbledsBbleds
31 gold badge1 silver badge2 bronze badges
0
1 Answer
Reset to default 4Because initial ypos is 0.It isn't updating.It remains zero all the time no matter how much you scroll down.To update it, it should be inside the see() function.So each time you scroll down the window, it will be updated.And it is working.Don't confuse it with "not working" statement.It was simply because,ypos variable was assigned to same "0" value.See my example .I have changed it.It will set the opacity to 0.4 when ypos>30
var x = document.getElementById('play');
var see = function() {
var ypos = window.pageYOffset;
if (ypos > 30) {
x.style.opacity = '0.4';
} else {
alert('scrolled more than 30 !!');
}
}
window.addEventListener("scroll", see);
<div style='width:600px;height:2000px;background:red;border:1px solid black;' id='play'>lol</div>