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?
Edit: the code I added didn’t work, that’s why I came for help.
4
Answers
Not sure what exactly your issue is here, your code is in general correct. Maybe checking the documentation for hasClass will help?
Alternatively you can use the pure-JS solution – classList, so the code will look like so:
You can rewrite the
checkClass()
function with vanilla JS like this:Since
contains()
returns a boolean, you can also simplify it to:Since you are only checking one element, you could also use
getElementById()
like this:As you can see, there are many different ways to do this in vanilla JS, but they all do the same thing.
This can easily be achieved using vanilla Javascript, but your code looks fine as is, that said, here is another solution which might make things clearer for you:
Simplified HTML:
Those functions set the color of the element body and change the class so we can use the same button to set it to dark or light
Is good to use ternary operator in cases like of "Yes or No"
Condition is true (if yes do this) : (if no do this)
One other way to solve that problem