Why doesn't the value appear on my input slider?

Viewed 70

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
}
1 Answers

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>

Related