0

Trying to code a simple equalizer in JS where user controllers the maxRadius with a slider but i keep getting this error

Uncaught TypeError: Cannot set property 'onchange' of null.

Here is my function:

maxRadius is a global variable declared.

 document.querySelector("#slider1").onchange = function(e) {
   console.log("value=" + e.target.value);
   document.querySelector("#sliderResults").innerHTML = e.target.value;
   maxRadius = e.target.value * 500;
 };

and here is my html

<div>
  <label for="slider1">Circle Size</label>
  <input id="slider1" type="range" min="0.1" max="1.0" step="0.1" value="0.5" />
  <span style="float:right" id="sliderResults"></span>
</div>
Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74
sap
  • 3
  • 1
  • 3
  • Make sure the DOM is ready before you access it. – Andrew Li Feb 20 '17 at 03:20
  • 1
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Andrew Li Feb 20 '17 at 03:21

2 Answers2

0

You just to make sure that document is ready

Try like this

function fn() {

  document.querySelector("#slider1").onchange = function(e) {
    console.log("value=" + e.target.value);
    document.querySelector("#sliderResults").innerHTML = e.target.value;
    maxRadius = e.target.value * 500;
  };

}

document.onreadystatechange = function() {
  if (document.readyState === 'complete') {
    fn();
  }
};

function fn() {

  document.querySelector("#slider1").onchange = function(e) {
    console.log("value=" + e.target.value);
    document.querySelector("#sliderResults").innerHTML = e.target.value;
    maxRadius = e.target.value * 500;
  };

}

document.onreadystatechange = function() {
  if (document.readyState === 'complete') {
    fn();
  }
};
<div>
  <label for="slider1">Circle Size</label>
  <input id="slider1" type="range" min="0.1" max="1.0" step="0.1" value="0.5" />
  <span style="float:right" id="sliderResults"></span>
</div>
Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74
0

Try this

document.getElementById("slider1").onchange = function(e)
        {
            console.log("value=" + e.target.value);
            document.querySelector("#sliderResults").innerHTML = e.target.value;
            maxRadius = e.target.value * 500;
        };
Haze Erasmo
  • 165
  • 7