2

Suppose I have 3 completely different layouts for one site. The first is shown by default, but there are hyperlinks at the top of the page. If you click one of them, I want the current stylesheet to be no longer used and the clicked one becomes applied to the HTML document.

I'm thinking this is done with Javascript, but can someone show me exactly how?

2 Answers 2

6

This article should answer your question. It relies on setting a stylesheet as a default one, then switching this out with alternate stylesheets, using the "alternate stylesheet" as the rel attribute instead of simply "stylesheet", along with a bit of Javascript.

Sign up to request clarification or add additional context in comments.

Comments

0

I needed to change CSS stylesheets dynamically, and it is very easy, if you know how to do it. Just simple HTML and vanilla Javascript. No round trip to the server (no POST, no GET).

CodePen demo here: https://codepen.io/r-w-c/pen/yLrjGOM

Github demo page here: https://r-w-c.github.io/Switching-Stylesheets-without-roundtrip-to-server

Files here: https://github.com/R-W-C/Switching-Stylesheets-without-roundtrip-to-server

index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dynamically load style sheet</title>
  <link rel="stylesheet" href="css/main.css">
  <link id="theme-link" rel="stylesheet" href="css/day.css">
</head>

<body>
<header>
    <input type="radio" id="day-theme" name="theme" checked>Day theme</a>&nbsp;
    <input type="radio" id="night-theme" name="theme">Night theme</a>
</header>
<main>
    <div>Hello world!</div>
</main>
   <script type="text/javascript">

        document.querySelectorAll("input[name='theme']").forEach((input) => { input.addEventListener('change', setStyleSheetHref); });

        function setStyleSheetHref(event)
        {
            document.getElementById('theme-link').setAttribute('href', event.target.id == 'day-theme' ? 'css/day.css' : 'css/night.css');
        }
   </script>
</body>
</html>

main.css:

main {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 500px;
  height: 500px;
  margin: 120px;
  border: 1px solid blue;
}

day.css:

main {
  background-color: white;
  color: black;
}

night.css:

main {
  background-color: black;
  color: white;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.