0

Maybe it's a silly question, but with:

var a = {
   scrolled: false
};

var handler = function() {
    a.scrolled = true;
    console.log(a.scrolled); // always "true"
};

window.addEventListener('scroll', handler);
console.log(a.scrolled); // always "false"

There is not a chance to change the value of a.scrolled from inside the event to the "outside" context?

Thanks....

AmintaCode
  • 364
  • 5
  • 15
  • Global variables are just that, global. You can always get to them. You just may need to fully qualify the reference using the browser's global object, `window`. – Scott Marcus Jul 21 '17 at 21:18

3 Answers3

2

Your handler triggers on scroll, and a.scrolled is false until you scroll. However, your console.log(a.scrolled) on line 11 runs when your JS is loaded, not once you've scrolled, so that will print false when your script begins.

Once you start scrolling, your other console.log(a.scrolled) on line 8 kicks in.

So what you'll see in your console is something like this:

false 
true 
true 
true 
true

The first false output is from line 11, the rest are from line 8, inside of the handler.

Ezra Chu
  • 832
  • 4
  • 13
0

Your code does change the value, and it does so globally (assuming your code is in the global scope).

console.log(a.scrolled); // always "false"

This is because you change the value when you change the value.

Changing the value does not time travel into the past and change it before you printed it to the console.

The output you printed in the past does not change.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I thought that when a scroll event happens, in that moment my global value, that I set initially as "false", would change... – AmintaCode Jul 21 '17 at 21:21
  • I think I get what you're trying to say, but your answer is really difficult to understand. Maybe it's the wording, but talking about "time travel" in programming just adds to the confusion, in my opinion. – Patrick Roberts Jul 21 '17 at 21:22
  • @AmintaCode — It does. The output you printed to the screen before you changed it doesn't. – Quentin Jul 21 '17 at 21:25
-1

Ok, thanks to all, in particular to @patrick-roberts that pointed me out the correct example. It's a matter of asynchronous code reference, but I would keep this question/answer as example because I think is simpler.

var a = {
     scrolled: false
};

var handler = function() {
    a.scrolled = true;
};

window.addEventListener('scroll', handler);

setTimeout(function() {
       console.log(a.scrolled)} 
       , 10000);

// a.scrolled is kept "false" if, in 10 seconds, no scroll event happens...
AmintaCode
  • 364
  • 5
  • 15