3

I have been trying to resolve this for a while, what is most confusing is, I am pretty sure the JS code is right. So I must be missing something, I have tried on Chrome and Mozilla.

So I have created the files locally in one folder, so I am sure they are connecting as the CSS is styling the page. I just cannot understand why the JS is not working nor why the value is not at least displaying 0.

JS:

var slider = document.getElementById("myRange");
var output = document.getElementById("value");

output.innerHTML = slider.value;

slider.oninput = function() {
    output.innerHTML = this.value;
}

HTML:

<html>
    <head>
        <script src="oslider.js"></script>
        <link rel="stylesheet" href="oslider.css">
    </head>
    <body>
        <div class="sliderContainer">
            <input type="range" min="1" max="10" value="1" id="myRange" class="slider">
        </div>
        <p>Value: <span id="value"></span> </p>
    </body>
</html>

CSS:

body {
    background-color:orange;
    color: white;
    font-family: 'Times New Roman', Times, serif;
    align-items: center;
}
p {
    margin-top: 50px;
}

.sliderContainer {
    width: 100%;
    margin-top: 200px
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
IK1987
  • 37
  • 5
  • 4
    Your script is running before the DOM has been built. – Andy Jul 12 '21 at 13:21
  • Either move your js at the bottom of body tag or register event DOMContentLoaded and call your js in the callback. – Aman Jul 12 '21 at 13:24
  • See [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Felix Kling Jul 12 '21 at 13:36

1 Answers1

4

You are there. Just write your code inside an event listener called DOMContentLoaded. Try this-

window.addEventListener('DOMContentLoaded', () => {
  var slider = document.getElementById("myRange");
  var output = document.getElementById("value");

  output.innerHTML = slider.value;

  slider.oninput = function() {
    output.innerHTML = this.value;
  } 
})
body {
    background-color:orange;
    color: white;
    font-family: 'Times New Roman', Times, serif;
    align-items: center;
}
p {
    margin-top: 50px;
}

.sliderContainer {
    width: 100%;
    margin-top: 200px
}
<div class="sliderContainer">
    <input type="range" min="1" max="10" value="1" id="myRange" class="slider"></div>
    <p>Value: <span id="value"></span> </p>
</body>
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
  • Thank you for your reply, so can you help understand why this JS code is not working? – IK1987 Jul 12 '21 at 16:34
  • You may attach your JS code at the head section or just before the `range` input field. So the JS is loaded and executed before the range input field is loaded. You can also make working your JS by adding a `defer` keyword on the `script` tag like `` – Sajeeb Ahamed Jul 13 '21 at 03:59