I want to make a feature for my website where the user can select the way the style will show up via a form.
I linked the form's elements to a JS file, but it doesn't work at all.
Here is the HTML code:
<form>
<label for="theme-selector">Select your theme:</label>
<select name="theme-selector" id="theme-selector">
<option value="auto">Automatic (default)</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<button id="apply-theme">Apply</button>
</form>
This is how I linked it to the script:
let theme = document.getElementById('theme-selector').value;
let applyBtn = document.getElementById('apply-theme');
let time = new Date();
time = time.getHours();
applyBtn.addEventListener('click', () => {
let node = document.createElement('link');
node.rel = 'stylesheet';
if(theme == 'auto') {
if(time >= 10 && time <= 19) {
// daytime theme
node.href = 'style/light.css';
}
else {
// nighttime theme
node.href = 'style/dark.css';
}
}
else {
// chosen theme
node.href = `style/${theme}.css`;
}
document.head.appendChild(node);
});
The "auto" thing is made so it will set different themes depending on what time is it.
I don't understand why it doesn't work. I am very new in JavaScript so please be kind, thanks!