Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Please explain to me why I can't define a variable let scroll =0; inside the event handler to hide and show the header

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;}
</style>
</head>
<body>
<div class="red" style="height:100px;position:sticky;top:0;width:100vw;background:red;"></div><div style="height:100vh;width:100vw;background:blue;"></div><div style="height:100vh;width:100vw;background:blue;"></div>
<script>let scroll = 0; //why I can't I define this variable inside the event handler,not glboal.
const red = document.querySelector('.red')
window.addEventListener('scroll' ,function(){
const scroll2 = window.pageYOffset;
if(scroll < scroll2){
red.style.top = "-100px"
}
else{red.style.top = "0"}
 scroll = scroll2
})
</script>
</body>
</html>

2 Answers

If you define let scroll = 0; inside the event handler, its scope will only be available when the event handler is called. So later when you set scroll = scroll2, the value in scroll will be lost once the function exits. It will be set back to zero every time the event is called, and not the value assigned from scroll2.

Can you please explain what scroll = scroll2 does.

When you scroll on this page, the event hander gets called and stores the current scroll position of the y axis into the variable scroll2 with the code 'const scroll2 = window.pageYOffset'. The variable scroll contains the y axis position from the previous time the page was scrolled. So using the math scroll < scroll2, the page knows if the page is scrolling down or up, Then decides whether to show or hide the red banner. So scroll = scroll2 is saving the current position of the y axis for next time the page is scrolled. It might be best to rename scroll to previousScroll and scroll2 to currentScroll to make it easier to follow.