I’m making a site for me to experiment and go out of my comfort zone and I’m trying to add a button that runs a different function based on whether or not it’s in dark or light theme using javaScript. I want it to work like this:
if elementClass == "dark"
run function 1
else if elementClass == "light"
run function 2
This is my current code
html:
<button id="fullscreen" class="fullscreen dark" onclick='checkClass()'> Fullscreen </button>
script:
function checkClass() {
if ($('.fullscreen').hasClass('dark') === true) {
openFullscreenDark()
} else if ($('.fullscreen').hasClass('light') === true){
openFullscreenLight()
}
}
The openfullscreen functions are working, however I don’t know how to properly check for classes as well as run a function in a function.
The if statements I found in another post and I don’t know how to use jQuery.
Is this possible to do? If so how?
>Solution :
You can rewrite the checkClass() function with vanilla JS like this:
function checkClass() {
if (document.querySelector('.fullscreen').classList.contains('dark') === true) {
openFullscreenDark()
} else if (document.querySelector('.fullscreen').classList.contains('light') === true){
openFullscreenLight()
}
}
Since contains() returns a boolean, you can also simplify it to:
function checkClass() {
if (document.querySelector('.fullscreen').classList.contains('dark')) {
openFullscreenDark()
} else if (document.querySelector('.fullscreen').classList.contains('light')){
openFullscreenLight()
}
}
Since you are only checking one element, you could also use getElementById() like this:
function checkClass() {
if (document.getElementById('fullscreen').classList.contains('dark')) {
openFullscreenDark()
} else if (document.getElementById('fullscreen').classList.contains('light')){
openFullscreenLight()
}
}
As you can see, there are many different ways to do this in vanilla JS, but they all do the same thing.