Let say i have created a slider and i am changing the value of slider using mouse. How can i use these values as variable in global scope, this variable should change to updated value when i changed the slider. I want to use the slider value in canvas to update my object.
HTML
<input id="slider" type="range" min="0" max="100" value="50" step="1" onchange="myFn()" >
JS
function myFn(){
let a = document.getElementbyId("slider").value;
console.log(a); //value change here how value is use outside the function.
}
CodePudding user response:
I think document.getElementById is getting invoked for every function call which is not an ideal. You can do like below.
// global scope
let inputEl = document.getElementById("slider");
let a;
function myFn() {
a = inputEl.value;
}
console.log(a); // as let is block scoped it can be accessed outside of the function or instead of let you can var keyword
CodePudding user response:
Your code is being misspelled: document.getElementById, letter b needs to be capitalized
Please try again with HTML:
<input id="slider" type="range" min="0" max="100" value="50" step="1">
and javascript
let slider = document.getElementById('slider');
slider.onchange = function(){
console.log(this.value)
}