Transform the CSS href attributes to different HTML pages when clicked

One interesting feature I am trying to implement on my website is the ability for users to select a color theme for their browsing experience. I have successfully created different themed external CSS files and even developed a function to seamlessly switch between all the available color options.

However, there seems to be a slight hiccup in this process. Whenever a user clicks on a link to navigate to another page within the site, the selected theme reverts back to the default color that was initially set up for that specific page.

I am now curious if there is a way to dynamically modify the href attribute of each HTML page so that the corresponding CSS color file changes across every page visited. Alternatively, could implementing cookies be a feasible solution to remember the selected color theme? Although I have not delved into the realm of cookies yet, I am contemplating whether they could serve as a viable solution.

Shown below is the code snippet that effectively switches between different color themes within a single page:

HTML: Orange Theme Purple Theme Red Theme

Javascript: function setStyleSheet(url) { var stylesheet = document.getElementById("stylesheet"); stylesheet.setAttribute('href', url); }

All necessary CSS files are stored externally. Any assistance or guidance on this matter would be highly appreciated. Thank you.

Answer №1

It is ideal to utilize cookies, but in the event that you are adamant about avoiding cookies, you can attempt running a script like this:

var links = document.querySelectorAll("a");

for (i = 0; i < links.length; i++) {
    var existingHref = links[i].href;
    links[i].href += (links[i].href.indexOf("?") + 1 ? "&" : "?") + "theme=" + encodeURIComponent(theme);
}

(This code has not been tested, and there are certain edge cases that need to be addressed, however, the basic concept remains)

This script will modify each link on the webpage by appending a theme=[theme] parameter to its URL. This information can then be retrieved on subsequent pages by extracting it from window.location.search:

function getTheme() {
    if (window.location.search.split("theme=").length < 2) return null;
    return window.location.search.split("theme=")[1].split("&")[0];
}

Please note that when I mention "ideally," I am emphasizing the importance of utilizing cookies - as they were specifically designed for and are commonly used for this purpose. With cookies, you wouldn't encounter issues such as pre-existing theme parameters in the URL or potential conflicts with other domains also using theme in their URLs. Cookies provide more reliable functionality even if you navigate between pages using Javascript. Nonetheless, this alternate method should function adequately as well.

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

When removing the class "img-responsive" from an image, the bootstrap columns begin to overlap

Just starting out with Bootstrap while working on an Angular2 project and I have a question. Currently, I have a map-component taking up 3 columns on the left-hand side, but every time I resize the browser, the image also resizes. I want the image to rema ...

"Printed documents fail to display underlined text using Bootstrap styling

Why do the codes show underlines on the webpage but not in the browser's print? This code is from the printOrder.blade.php file: <!DOCTYPE html> <html dir="ltr" lang="en"> <head> <meta charset="UTF-8&qu ...

Upon selecting the display image option

Here is a jsfiddle file provided for your reference. I am attempting to create a functionality where upon clicking buttons (1,2,3,4), the corresponding image shows up and overlaps with any previously displayed images. I have tried using the following code ...

What could be causing getStaticProps to receive an incorrect slug value?

Currently, I am encountering an issue with obtaining the correct slug in getStaticProps(). My goal is to retrieve the translated slug for a specific page (for example: the about page). The getStaticPaths() function is able to generate the correct object. ...

Koa and supertest experiencing delays when sending multiple post requests

My current challenge involves implementing multiple post requests on a koa server using supertest. The issue arises when running the code snippet below with the mentioned command. Upon execution, the script hangs during the dispatching of the second post r ...

Abstraction of middleware functions

After reviewing my middleware Express functions, I realized that there is repeated code. The first function is as follows: const isAdmin = async (req, res, next) => { try { const requestingUser = await knex('users') ...

Effective methods to prevent the `translate` transform from triggering an element to be perceived as position relative?

I am encountering an issue with an absolutely positioned div that is nested within a statically-positioned parent container. I noticed that when I apply the transform: translateY(-50%) property to the container, the child element behaves as if it were bein ...

There seems to be an issue with the functionality of the AJAX file upload feature in

I've developed a method for file uploading using AJAX technology (pure JavaScript) in CodeIgniter. Here's how it works: 1- I created a script.js file to manage the AJAX/JavaScript upload process. 2- I implemented a controller in CodeIgniter to ...

Instructions on utilizing jQuery to compare individual numbers within an array and hiding a div tag if the number is less than the specified range input

I have encountered an issue with Array manipulation in jQuery. Below is the code snippet that I am working with: Within my HTML structure, I have div tags with the same class but different values in their span tags. I am using an input range bar to dyna ...

Show some text when the ReactJS icon is hovered over

As a beginner with React, I am trying to show text when the user hovers over an icon. Currently, I am using material-ui along with the latest version of Reactjs. Below is the code snippet that I last tried: return ( <List className={classes.list ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...

Issue arises during initialization with Slick.js

I recently attempted to implement the slick.js function on my webpage by following the guidelines provided on . I copied the "center mode" function as my Jquery function, but unfortunately, the arrows/buttons and nav-docs were not generated in my slideshow ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

Choosing an option will display a specific div while hiding another using JQuery

My question involves a Select Option <select class="input_select" name="customer_type" id="central_company"> <option value="standard">Standard</option> <option value="central">Central Station</option> </select> ...

The element remains stationary and does not shift positions

My form is not centralizing properly, it seems to be stuck to the left side of #wrapper. I've tried adjusting margin-top but it doesn't seem to affect its horizontal position at all. I've played around with different values for margin and ev ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Eliminate the final two digits from each element in the array if they exceed two digits

A challenge I am facing involves an array with multiple elements. My goal is to remove the last two digits from any element in the array that consists of 3 or 4 digits, while leaving elements with 1 or 2 digits unchanged. var test =[ 2, 45,567, 3, 6754]; ...

Instructions for highlighting a dynamically added UL Li element for a brief 3-5 seconds after clicking a button

When I click a button, I dynamically add UL and LI elements. After they are added, I want to show them highlighted on the user interface for a brief period, like 3-6 seconds. ...

How can I position the nav-item to the right without it becoming collapsed?

Hello! I am currently using Bootstrap 4 and attempting to create a navbar menu. Below is the code I have written: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" da ...

Tips for utilizing the if-else directive in an AngularJS controller

My current challenge involves HTML coding. <li><strong>Scrub:</strong> {{insuredProfile.permanentAddress.isScrubbed}}</li> This code displays either true or false. I want to show Yes for true and No for false. Using data-ng-if, ...