Why is this javascript if statement not working?
On 8/9/2019 at 8:57 PM, Crispybagel said:Trying to get it to work with a Pen but i can't figure it out :s...
https://codepen.io/niklas-bagge/pen/mNGYMg
Well the very first problem is that you are selecting your block by id div where it should be block and the second mistake is comparison in the if statement with = (it actually does an assignment) instead of == - which does the comparison of equality.
But the main reason that this code does not work is that it gets executed only once when you run the program (reload the page) and that's it. When you're changing (moving) the slider the code is not executed "again" to go through the if statement and so on. In other words moving the slider does not trigger the code to run again.
To execute some code on the event of slider being moved you need an event listener. Every element in the DOM fires events on various occasions, like when the button is clicked or the slider is moved, and we can "listen" to those events and execute code after they fire by attaching an event listener to the element that we're interested in. In this case it's the slider.
Here's an update of your JS code for that codepen example:
var slider = document.getElementById("slider"); var block = document.getElementById("block"); slider.addEventListener('change', onSliderValueChange); function onSliderValueChange() { if (slider.value === "2") { block.style.background = "blue"; } }
I have attached an event listener to the slider element using the addEventListener method and passed two arguments into it:
'change' - name of the event that we want to listen on and a reference to a function onSliderValueChange that will be executed each time the value of the slider changes (hence that change event). Now when we move the slider the slider element will fire events, our event listener will handle those by executing the onSliderValueChange function and the code in that function will change the background of the block when the value is exactly '2'. Note the triple equal sign - this means that we're not only shallow comparing the value but also comparing the type of it... but that's a story for another day Good luck coding!
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now