-2

This is the code i have. I want to have my global variable store and update (with events) the value of a range slider. As you can see, i declared a global variable 'valueA' and changed it inside the function 'on' via jQuery. It's important to note that this.value is NOT undefined and it changes its value every event, as intended. But when I console log valueA after the function that should change it, it returns 0, as if nothing was changed.

var valueA = 0;

var value = $('#myRange');

value.on('input', function(){
    valueA = this.value;
});

console.log(valueA)
Dvali
  • 7
  • 1
  • 4
  • `valueA = this.value;` happens after `console.log(valueA)` –  Jun 09 '21 at 13:45
  • Think about what this code is doing. The first two and last line of code run when the page loads. The fourth line runs when a value is entered in to the input *after* the page has been loaded. – Rory McCrossan Jun 09 '21 at 13:48
  • @RoryMcCrossan ok, I get it. How should I change it to make it work? – Dvali Jun 09 '21 at 14:26
  • Put the `console.log()` line inside the `input` event handler, and [do not use global variables](https://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice). If you need to pass data structures around, create functions and pass the data as parameters. – Rory McCrossan Jun 09 '21 at 14:30
  • @RoryMcCrossan yes, I need it to pass to somewhere outside the function, is it possible for you to show how can I do this in code? – Dvali Jun 09 '21 at 14:35
  • @RoryMcCrossan I am new at this stuff, sorry – Dvali Jun 09 '21 at 14:36
  • From within the input handler: `yourOtherFunction(this.value)`. I'd suggest researching a tutorial on how to create and work with functions in JS if this is new to you. – Rory McCrossan Jun 09 '21 at 14:42
  • @RoryMcCrossan I’ve done this exact thing before, but the problem is, I need a variable that is outside that function to take that value... And if I’m passing it to another function, I still need to access the returned value outside of that. I’m not new to functions, it’s just the first time I deal with thing kind of thing, haven’t had problems before like this. – Dvali Jun 09 '21 at 14:56
  • In that case it sounds like you need to restructure the logic of your system as you should absolutely not be relying on globals. – Rory McCrossan Jun 09 '21 at 15:01

1 Answers1

2

For real it change, with your code it is 0 because you declare as it and change when change the range.

var valueA = 0;

var value = $('#myRange');

value.on('input', function() {
  valueA = this.value;
});
document.querySelector('button').addEventListener('click', () => {
  ConsoleMe()
});

function ConsoleMe() {
  console.log(valueA)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='range' id='myRange'>
<button>Click me before change range</button>
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34