Basic DOM scrolling question

I’m trying to understand how the scroll events work in js, and wrote this simple code to see if when I scroll down the webpage I get notified in the console:

const showAlert = () => {
    if(window.pageYOffset > 500) {
		console.log('yes')
	} else {
		console.log('no')
	}
}
window.onscroll = showAlert;

However nothing shows up in the console when I scroll…
Am I missing something really basic?

Thanks

I think you do, because there’s nothing wrong with the script.
Is your script linked correctly? Can you console log something at all?
Also, your page does have a scrollbar, right?

1 Like

I think it is linked correctly because other js functions are able to load and console.log properly… I am just testing this out because I want to do something with the scroll event eventually and thought I’d start with the basic step.
I will have to try and figure this out :thinking: :thinking: Thanks.

Does
document.addEventListener("scroll", () =>{console.log(window.pageYOffset)})
change anything?

1 Like

Yes the below worked! So it means the event listener works but not onscroll…
That’s weird because in a different place in my code I have used the onscroll and it works… JS is so confusing :grimacing:

document.addEventListener("scroll", () =>{
	if(window.pageYOffset > 500){
		console.log('ok')
	} else {
		console.log('no')
	}
});

Your original method of using the onscroll event works. This is what I just did and it works fine:

<script>
  const showAlert = () => {
    if(window.pageYOffset > 500) {
		console.log('yes')
	} else {
		console.log('no')
	}
}
window.onscroll = showAlert;
</script>
<div class="outer" style="height: 100em"></div>

I’m not sure why it wouldn’t work for you. I think maybe we aren’t getting all the info we need here?

1 Like