Select background with dropdown menu
Select background with dropdown menu
I'm making a simple HTML5/CSS3/JS website which involves changing the theme (background) with a dropdown menu. However, my code does nothing.
<div id="theme-picker">
<form action="">
<select name="themakeuze" id="thema" onchange="changeTheme();">
<option value="dark" >Donker thema</option>
<option value="light">Licht thema</option>
</select>
</form>
</div>
<script type="text/javascript">
function changeTheme()
{
var e = document.getElementById("thema");
var strUser = e.options[e.selectedIndex].text;
if (strUser == "Donker thema")
{
document.body.style.backgroundImage = 'url(img/binding_dark.png)';
}
if (strUser == "Licht thema")
{
document.body.style.backgroundImage = 'url(img/binding_light.png)';
}
}
</script>
I'm obviously not very good at JavaScript. We're not allowed any libraries.
the form id is also "thema". It's a dutch word, not a typo. Thanks.
– Cinaed666
Jan 3 '14 at 14:48
3 Answers
3
(1) The onchange
event should be applied to the select
itself:
onchange
select
<select name="thema" id="thema" onchange="changeTheme();">
<option value="dark">Donker thema</option>
<option value="light">Licht thema</option>
</select>
(2) The following lines should be placed inside the function changeTheme()
rather than outside it:
changeTheme()
var e = document.getElementById("thema");
var strUser = e.options[e.selectedIndex].text;
(3) The if
statement should be properly written as:
if
if (strUser == "dark")
Ahh yes, that makes more sense already, though it still doesn't work. I've updated the code in the original post.
– Cinaed666
Jan 3 '14 at 14:40
@user2820952 You have a conflicting name / id in the
select
.. Change the name to something like Mythema
or something else... It should work fine then..– Skindeep2366
Jan 3 '14 at 14:54
select
Mythema
thanks, it's working now!
– Cinaed666
Jan 3 '14 at 14:55
@user2820952 You’re welcome.
– user2680766
Jan 3 '14 at 14:55
change the code and set onchange="changeTheme()" on the Select not in the option
Also prepend "document" where you try to set the background.
document.body.style.backgroundImage = 'url(img/binding_dark.png)';
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Spelling mistake in 'document.getElementById("thema");'. Check please. 'thema' should be 'theme'
– ram
Jan 3 '14 at 14:29