change document stylesheet with select tag in javascript
I have a drop down box on my website that lets you select your theme. The problem is that I can't figure out how to implement it. Here's the javascript:
//selects the select element
let selectTheme = document.querySelector("#select-theme");
//selects the stylesheet
let style = document.querySelector("#pagestyle");
selectTheme.addEventListener('onchange', () => {
if (selectTheme.value == "dark") {
style.setAttribute("href", "./css/style.css");
}
if (selectTheme.value == "light") {
style.setAttribute("href", "./css/style2.css");
}
console.log(selectTheme.value);
})
HTML:
<link rel="stylesheet" type="text/css" href="" id="pagestyle">
<div class="selection-box">
<select class="select-theme" name="selectTheme" id="select-theme">
<option value="dark" id="dark">dark</option>
<option value="light" id="light">light</option>
</select>
</div>
The even listener itself doesn't seem to work, as it doesn't print out the drop down value.
Also note that this isn't all of my HTML. I just copied and pasted the relevant elements.
Solution 1:
The eventlistener is change
not onchange
Once you change it your console.log will work
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event