krozshardt
krozshardt

Reputation: 19

Changing a stylesheet through javascript

I am trying to change the stylesheet of my page through a javascript function. It does work at first, but after 2 clicks the variable defining the non-active stylesheet gets stuck on the "dark" value.

I would be very grateful if I received support from this amazing community. ^^

Here you have both the page and the source code:

Link: https://jadeblink.netlify.app

HTML

<head>
    <title>JADEblink*</title>
    <link rel="stylesheet" id="pagestyle" href="dark.css">
    <link rel="alternate stylesheet" id="pagestyle" href="light.css">
    <script src="main.js"></script>
</head>
<body>
    <div id="pagetitle">
        JADE<span id="blink">blink*</span>
        <div class="shape" onclick="changeStyle();">Change to<br><span id="xstyle"></span> style<div>
        <script>
            var t=setInterval(function(){document.getElementById("xstyle").innerHTML=otherstyle;},100);
        </script>
    </div>
</body>

JavaScript

var otherstyle="light";
function changeStyle() {
    document.getElementById('pagestyle').setAttribute('href', otherstyle+".css");
    if(otherstyle="dark")
        otherstyle="light";
    if(otherstyle="light")
        otherstyle="dark";
}

Upvotes: 2

Views: 64

Answers (1)

CapitanFindus
CapitanFindus

Reputation: 1526

There's something wrong in your logic.

Using if(otherstyle="dark") won't compare it, as you need to use == to compare, or === for a strict comparison.

Apart from that, if you're setting it to light, it will enter your next if condition, restoring it to dark, so you need to use an else if for the second condition.

This should do the trick:

var otherstyle = "light";

function changeStyle() {
  document.getElementById('pagestyle').setAttribute('href', otherstyle + ".css");
  if (otherstyle == "dark")
    otherstyle = "light";
  else if (otherstyle == "light")
    otherstyle = "dark";
}

Upvotes: 4

Related Questions