More on the DOM
Toggle switches
-
There's only two parts to this:
- writing out the function
- Using onclick on an HTML element to use as a toggle switch
-
The function
We write out the function to target a div with id of content:
function toggleContent() { let contentId = document.getElementById("content"); contentId.style.display == "block" ? contentId.style.display = "none" : contentId.style.display = "block"; }
The button tag uses
onclick
. Any element could be used, not just <button>And
onclick="toggleContent()"
wheretoggleContent
is the function we wrote.This came from Wikihow.com
-
The code used:
- The block is turned to
display: none
in the CSS. getDocumentbyID
is used to target the div element which has an:id="content"
?
is combined with the:
here. This is the ternary operator: a shorthand of an If / else statement. The first part before the?
is the condition to be met. It is either true or false. The next bit after the question mark, is code to be executed. If it's false the the code after the colon is executed. More...==
means equals.style
to target the CSS of this particular element.- The starting position (ie. hidden) was defined in the CSS for #content.
- The block is turned to
Toggling classes
It's also possible to toggle classes on an element. In other words adding and then removing a class from an element. This is done using the built in toggle
which is part of the classList()
method.
See the page on modifying the DOM
It's also possible to toggle the name of a class on an element using className
with an if
statement.
if (element.className == "myStyle") {
element.className = "newStyle";
}
else {
element.className = "myStyle";
}