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 One Solution

When we should declare our variable inside the event handler and when we should declare them global.

I working on a project, but I could not figure out why I have to declare the variable global because If I did not declare the inside the handler, it won't work.

2 Answers

Steven Parker
Steven Parker
231,261 Points

The concept that determines where variables should be declared is called "scope". If a variable is used only within a function, it is said to have "function scope" and it would be appropriate to declare it within the function. But a variable used both inside the function and outside would need to have "global scope" and be declared globally.

If you need more specific help, you can show the actual code.

Steven Parker
Steven Parker
231,261 Points

If you're referring to the variable "red", it seems to be used only inside the handler function so it would make sense to define it there. There's no need to make it global.

I am trying to implement a cool behavior as you scroll up the header appear and disappear when I scroll down, but I could not figure out why I have to define a variable called const scroll = 0 global because It does not work If I define that variable inside event handler. Can someone explain to me when I have to define global variable and when I. have to define my variable inside event handler when working manipulated the DOM.

```<!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> const red = document.querySelector('.red') window.addEventListener('scroll' ,function(){let scroll = 0; const scroll2 = window.pageYOffset; if(scroll < scroll2){ red.style.top = "-100px" } else{red.style.top = "0"} scroll = scroll2 }) </script> </body> </html>