-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)
9
  • valueA = this.value; happens after console.log(valueA)
    – user15388024
    Jun 9, 2021 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. Jun 9, 2021 at 13:48
  • @RoryMcCrossan ok, I get it. How should I change it to make it work?
    – Dvali
    Jun 9, 2021 at 14:26
  • Put the console.log() line inside the input event handler, and do not use global variables. If you need to pass data structures around, create functions and pass the data as parameters. Jun 9, 2021 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 9, 2021 at 14:35

1 Answer 1

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>

3
  • But how can I make it so it is changed globally? Whatever I declare it stays the same for some reason.
    – Dvali
    Jun 9, 2021 at 14:29
  • Is changed globally Jun 9, 2021 at 18:43
  • @Dvali i change my snippet and add a simple button, when you change slider and press button you will see is change outside the function so is globally. Jun 10, 2021 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.