Just a heads up, I'm not using classes in this particular scenario. Can't seem to find the answer to this exact question.
With javascript, how can I code a button to switch stylesheets every time it's clicked?
I've experimented with different if, else if and else statements, but they always end up breaking the code (e.g., changing color to blue from red, but failing to revert back). It works fine with two buttons, but making it work with just one seems to be a challenge. In frustration, I added a second button to reset it back.
Here's the solution for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
Moving forward, looking to streamline it down to one button and function.
UPDATE... Attempted this approach, unfortunately didn't work out as planned.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}