Press the toggle switch button to easily switch between two distinct stylesheets

With a looming exam at university, my web design professor has tasked us with creating a website. The unique challenge is to implement a style change by seamlessly switching between two different CSS stylesheets. My idea is to start with a black and white version as the default and then introduce a toggle switch button that transitions to a colored version.

Although I've successfully created the button in my HTML code snippet, I'm now struggling with understanding how to link and smoothly transition from one stylesheet to another using JavaScript. Here is the HTML portion for the button:

.switch {
  position: relative;
  height: 34px;
  width: 60px;
  display: inline-block;
  }
.switch input {
  display: none;
  }
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: white;
  border-radius: 26px;
  transition: 0.4s;
  }
.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  border-radius: 50%;
  background-color: black;
  left: 4px;
  top: 4px;
  transition: 0.4s;
  }
input:checked + .slider {
  background-color: #fffe54;
  }
input:checked + .slider:before {
  transform: translateX(26px);
  }
<label class="switch">
  <input type="checkbox">
  <span class="slider"></span>
</label>

If anyone can offer guidance or assistance, it would be greatly appreciated!

Answer №1

I stumbled upon this discussion: How can I dynamically change the CSS stylesheet for a website currently being viewed?

Various solutions are provided in the conversation, so give them a try and see if any of them suit your needs.

Answer №2

To optimize the design of your website, consider setting a default class for the body element. Then, upon clicking a button, switch classes to apply different styles. Clicking back on the button will revert to the default class.

By using this method, you can load both stylesheets but only utilize one at a time.

Alternatively, you could just load one stylesheet with varying styles.

If you're interested in seeing an example of how to implement this technique, check out this resource on w3schools.

Answer №3

Here is a demonstration of how you can easily switch between style sheets.

To accomplish this, you will need to create two separate style files - one named `style.red.css` and the other named `style.blue.css`. These files will be used to change the color theme of your webpage.

For convenience, it's recommended to save this functionality in local storage so that the user's preference is remembered even when navigating to different pages. I have already implemented this feature for you as well.

const button = document.querySelector('button');
const type = 'red';

const headStyle = (type) => {
  const head = document.getElementsByTagName('head')[0];
  const style = document.createElement('link');
  style.rel = 'stylesheet';
  style.id = 'colorTheme';
  style.href = `./style.${type}.css`;
  head.appendChild(style);
  document.documentElement.setAttribute('data-theme', type)
  console.log(style);
}

button.addEventListener('click', () => {
  const colorTheme = document.querySelector('#colorTheme');
  colorTheme.parentNode.removeChild(colorTheme);
  const typeTheme = document.documentElement.getAttribute('data-theme');
  typeTheme === 'red' ? headStyle('blue') : headStyle('red')
})

window.addEventListener('load', headStyle(type));
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>switch</button>
  <script src="./script.js"></script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Order Up: Vue Draggable Next feature keeps your lists in line

I need to maintain the order of two lists in local storage so that their positions are saved and retrieved between sessions. In my Vue 3 TS project, I am utilizing this library. Check out the code snippet below: <template> <div> <h3> ...

Resetting the internal state in Material UI React Autocomplete: A step-by-step guide

My objective is to refresh the internal state of Autocomplete, a component in Material-UI. My custom component gets rendered N number of times in each cycle. {branches.map((branch, index) => { return ( <BranchSetting key={ind ...

Can the (Bootstrap) popover cause a button to shift position?

<- this is where my website is located After clicking the '*로그인' button, it seems to redirect to the '*가입하기' button. Is there a way to prevent the button from moving when clicked? *('로그인' translates t ...

What steps can be taken to remove the search parameter responsible for the error?

Imagine having a webpage that displays search results based on the parameters in the URL, like this: https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3 This URL will show listings for only brand1, brand2, and brand3. Additionally ...

Guide on how to navigate to the bottom of a div element using Selenium Webdriver

My current project involves a unique challenge where there is a specific div element on the webpage that acts as a popup dialog when a link is clicked (similar to Facebook reaction dialog boxes). To automate tests for this scenario, I am using Selenium We ...

Utilize React JS to parse and display a sophisticated JSON structure in a dropdown menu

Looking at the backend data structure provided, we have information on various courses in different departments. { "courseDetails" : [{"departmentId" : 105654, "courses" : [{"stream" : "science","courseIds" : ["104","105 ...

"Why does the useEffect in Next.js fire each time I navigate to a new route

Currently, I have implemented a useEffect function within the Layout component. This function is responsible for fetching my userData and storing it in the redux-store. However, I have noticed that this function gets triggered every time there is a route c ...

What is the best method for getting rid of blank white space on my website?

Having some trouble removing unnecessary white space on my website. The goal is to have the main text and logo centered on an image background, but I've been unsuccessful so far. I've experimented with different CSS properties like overflow-x: ...

Exploring the process of creating a interactive rectangular border on an image with JavaScript

I'm currently working on a project that requires me to draw multiple bounding boxes interactively within an image displayed on a web browser. After drawing the bounding boxes, I will need to extract their coordinates. Are there any suggestions for a J ...

Configuring the default value for a selection menu in Vue3

Obtaining all available categories: const fetchCategories = async () => { let response = await axios.get(`/api/get_all_category/`) categories.value = response.data.categories } The structure of categories.value is shown here: https://i.sstatic.net ...

How can I create a one-column layout in CSS grid where one element automatically fills the remaining space after the other elements have taken their own auto widths?

I want a flexible layout with auto width columns for future additions. Avoiding extra wrappers is preferred. CSS grid is the preferred method over flexbox (although flexbox can achieve it with wrappers). This layout is intended for a navigation bar Here&a ...

The functionality of the disabled and checked options on the radio button seems to be malfunction

Within an Angular HTML document, I have a set of radio buttons that share common names. I am attempting to update their disabled and checked properties from a .ts file, but the changes are not taking effect. Here is the code snippet: let elements = docume ...

Is there a way to substitute the function variable using JavaScript?

Is there a method to dynamically replace the variable 'abc' with 'cde' in HTML using JavaScript? For example, if I have the following code: <table width="150" border="0" cellspacing="0" cellpadding="2" id="productBox"> <tr> ...

Utilizing an NPM package in your project

Trying to incorporate a node module called "tagify" into my node.js application has been challenging. Following the instructions in the package's readme file (https://www.npmjs.com/package/@yaireo/tagify#installation), I executed the setup steps as ou ...

How can I represent the square bracket character using regex in JavaScript?

I'm trying to figure out how to create a regex for square brackets ( [ ] ) in JavaScript. Any advice? ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Adding an exception for ClickAwayListener in React-MUI

Hey there! I'm currently exploring MUI and trying to incorporate the ClickAwayListener API into my project, but I'm facing some difficulties. You can take a look at my project on codesandbox here: https://codesandbox.io/s/react-leaflet-icon-ma ...

Setting header details for optimal data transfer

Currently, there is a Java code snippet that I am working on which attempts to access the header information sent by an HTML page. Unfortunately, I do not currently have the specific HTML page in question. However, I still need to be able to access and m ...

What could be causing my MongoDB Node.js driver's $lookup aggregation query to not produce the expected results?

In my database, I have two collections: users and roles Each user has an array of roles assigned to them: { _id : 61582a79fd033339c73ee290 roles:[615825966bc7d715021ce8fc, 615825966bc7d715021ce8fd] } The roles are defined as follows: [ { ...

What is the correct method to authenticate a user's ID token in Firestore with Javascript?

I am in the process of developing a react native application and have integrated Firebase, specifically firestore, for data management purposes. My current goal is to incorporate an automatic login feature in my app, where users remain signed in even after ...