0

I have this script

var x = 0;

document.addEventListener('DOMContentLoaded', function() {

  const button = document.getElementById('my-button')
  button.addEventListener('click', () => myFunction(x));

});

function myFunction(x) {
  console.log(x)
  x++
}

I need that when I click the button, myFunction receives the current value of x and not the value that was assigned when the function was added (0 in this case), the thing is that I have another function that is constantly updating the value of x, but if console.log the value of x within myFunction I always get 0. Probably there is a straightforward solution but I'm really struggling with this and my skills with JS are very limited.

Carlos S. C.
  • 101
  • 7
  • That should work. After whatever else changes `x`, the next click of the button will see the updated value in `myFunction` – CertainPerformance Jan 04 '23 at 01:41
  • See [What is the scope of variables in JavaScript?](/q/500431/4642212), [edit] your post, and provide a [mre]. – Sebastian Simon Jan 04 '23 at 01:42
  • `document.addEventListener('DOMContentLoaded', function() {...}` is a weird way to me of waiting for the DOM to load to add the event listener... look into document.onload, window.onload, or something like that. That's probably neither here nor there, but your `myFunction(x)` just needs to be `myFunction()` and the event listener on the button doesn't need to have `(x)`. So recap -> `function myFunction() {...}` and `button.addEventListener('click', myFunction);` – Shmack Jan 04 '23 at 01:48
  • 2
    `x++` increments the passed parameter `x` which is shadowing the the outer variable. Just don't have it accept a parameter and it will find the global. – pilchard Jan 04 '23 at 01:48
  • `x++` modifies the parameter `x`, not the global variable `x`. Don’t accept parameters, don’t pass arguments. – Sebastian Simon Jan 04 '23 at 01:50
  • @Shmack `DOMContentLoaded` really is the best way *if* you're doing it with JS. I'd prefer to remove the need to do it entirely though with the `defer` attribute in the HTML. – CertainPerformance Jan 04 '23 at 01:53

0 Answers0