I'm currently trying to design a page on WordPress in which I would like to implement a night-mode.
Basically, when you press a button(image), the background color will change from white to black (later on, also the text color).
I have to use inline-css and JavaScript because of WordPress. Right now, I am trying this code:
<script type="text/javascript">
var activated = 0;
function changeBgCol()
{
if (activated == 0)
{
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
activated = 1;
}
else
{
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
activated = 0;
}
}
</script>
and the button(image):
<a><img class="alignnone size-medium wp-image-2591" onclick="javascript:changeBgColor()" src="https://www.[WEBSITE].se/main/wp-content/uploads/2013/11/[PICTURE]-300x300.png" width="480" height="480" /></a>
But when I test, it, the image is not clickable and the background color doesnt change.
What could be the issue?
Best regards
The best way is to toggle a class on the body.
$('.yourbutton').on('click', function(){
$('body').toggleClass('theme--dark');
});
Then just add the corresponding CSS.
.theme--dark {
background-color: #111;
}
You had the onClick event set to changeBgColor, and the function in the JavaScript set to changeBgCol. Always check your developer console whenever you run into problems getting a script to work. Try this:
<a><img class="alignnone size-medium wp-image-2591" onclick="javascript:changeBgCol()" src="https://www.[WEBSITE].se/main/wp-content/uploads/2013/11/[PICTURE]-300x300.png" width="480" height="480" /></a>
<script>
var activated = 0;
function changeBgCol() {
if (activated == 0) {
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
activated = 1;
} else {
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
activated = 0;
}
}
</script>
It's not generally considered best practice to use inline scripts. You might want to try something like this instead going forward: https://jsfiddle.net/eL46ch5y/ or use jQuery .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.