Attempting to toggle between four different stylesheets by utilizing a button and javascript functionality

After searching around, I have managed to find solutions on toggling between 2 CSS files. However, my requirement is a bit different - I need to use just one button to switch between 4 distinct CSS files. The primary CSS file that is loaded with the HTML is named style1.css.

I came across a JavaScript snippet that achieves a similar functionality with images. Essentially, it works by placing all the images in an array and moving the first image to the end of the array for rotation. Here's how I implemented it:

var imageUrls = ["images/paulfr.jpg", "images/johnfr.jpg", 
"images/georgefr.jpg", "images/ringofr.jpg"];

function changeImage(){
    var img = document.getElementById('image');
    var imageUrl = imageUrls.shift();
    img.src = imageUrl;
    imageUrls.push(imageUrl);
}

So, I attempted to adapt this concept for stylesheet files but encountered some issues:

var stylesUrls = ["css/style1.css", "css/style2.css", 
"css/style3.css", "css/style4.css"];

function changeStylesheet(){
    var style = document.getElementById('styles');
    var stylesUrl = stylesUrls.shift();
    style.src = stylesUrl;
    stylesUrls.push(stylesUrl);
}

I made sure that the stylesheet id is set to 'styles'. Can someone please assist me in identifying where I went wrong?

Answer №1

Modify the src attribute to href:

style.src = stylesUrl;

to

style.href = stylesUrl;

Complete solution:

var stylesUrls = ["css/style1.css", "css/style2.css", 
"css/style3.css", "css/style4.css"];

      window.onload = function(){
           var refButton = document.getElementById("change-styles");

            refButton.onclick = function() {
                      var style = document.getElementById('styles');
                      var stylesUrl = stylesUrls.shift();
                      style.href = stylesUrl;
                      stylesUrls.push(stylesUrl);
                  
            }
        };

HTML

<link href="css/style1.css" rel="stylesheet" id="styles" type="text/css">

<a href="#" id="change-styles">Change</a>

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

Monitoring web traffic on an AJAX website using Google Analytics

Is it possible for Google Analytics to track pageviews if the URL of a page changes dynamically using Javascript? For instance, let's say I visit the page example.com/about(1 pageview) in my browser. Then, I click on the "contacts" link, but instead ...

tips for transferring API JSON response parameters to material ui table

I'm currently working on creating a table with the material UI. My goal is to populate the rows of the table based on the data received from an API response. The challenge I'm facing is that the API response includes an array of objects with mult ...

Effective methods for eliminating Stripe's iframes

I am integrating Stripe Elements using vue-stripe-elements-plus on a single page application. I want to completely unload Stripe after the user leaves the credit card module, but it seems more complicated than expected. Even after unloading it in the comp ...

Guide to collapsing all menus in an Angular 4 Accordion

I am a beginner with Angular 4 and I have implemented an accordion with the structure of Categories, Groups, and Subgroups. When I click on a category, it displays all the groups within that category. Similarly, when I click on a group, it shows all the s ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

Improving efficiency in protractor click tests by implementing For-Loops

Query: How can I successfully click on each link within a ul > li a in one single test? Issue: Although the test is currently passing, it is not effectively clicking on the links. This can be verified by the absence of redirection or the expected 2000m ...

SCRAM-SERVER-FIRST-MESSAGE: The client's password is required to be in string format

After researching documentation from various sources on a similar issue, I have not been successful in resolving this specific error within my code. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string') ^ ...

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

The error seems to vanish when commenting out the following div structure

Since upgrading to Angular 5, I've been encountering the following error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: undefined'. Current value: 'ngIf: null&apo ...

Express server consistently receives JSON requests that contain no data in the request body

Currently, I am in the process of developing a small server and website using Express. At this point, my goal is to send a POST request to my Express server with basic credentials encoded as JSON. The issue I am facing is that no matter what I attempt, th ...

Animating rows to smoothly glide across the screen

I have created a container with four rows, each containing a different number of columns. When I click on a row, it should move to the next row. However, when I click on the final row (which is in the last position), it should wrap around and move to the ...

Utilize React.js to embed an iFrame video using YouTube's JavaScript API

Despite scouring for examples, all I could find were youtube-react and npm packages that I'm not interested in using. My intention is to learn and implement it on my own. The issue lies with the guidance provided in the documentation found here: http ...

Grab an HTML table and store it in a JavaScript variable using jQuery

I need help with backing up and filtering an html table using jquery. $('.row').closest('td').not(':contains(' + v + ')').parent('tr').remove(); Because of the remove() function, I want to create a backup ...

Difficulty encountered when applying border-radius to a fixed image

One interesting thing I tried was anchoring an img tag with its own link and then styling it using the following CSS code: a{ border-color: white; border-width: 2px; border-radius: 50%; border-style: solid; } The result was qui ...

Cleaning up unwanted objects in THREE.js webGL

Our app utilizes THREE.js to showcase 3D body meshes. We have a special object named MeshViewer that manages the rendering process; within the initialize method, we establish this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBu ...

Ensure that it is safe to bypass Vue's built-in sanitization on this specific Vue component for the href attribute

I encountered an issue with a .vue file that contains an anchor tag as shown below: <a class="login_class" :href="loginUrl">Use Universal Login</a> When running Sonar, it raises a warning regarding the :href attribute: En ...

JavaScript Build Failure: Linting Error Detected - no-constant-condition

I am encountering an error labeled as Unexpected constant condition no-constant-condition when attempting to compile this code. (The error is on a line indicated with >>>) This code operates based on user input. The variables commandVariable0 and ...

Building a concealed navigation bar using HTML and Typescript that appears when you start scrolling - here's how!

Seeking guidance on creating a hidden navbar that becomes visible as you scroll the page, using TypeScript. Can anyone provide assistance? <nav class="navbar navbar-expand-lg navbar-dark pb_navbar pb_scrolled-light w3-animate-right navlist-right ...

ngStorage in AngularJS app does not retain sessionStorage data

Hello everyone, I am currently facing an issue with storing a user object in sessionStorage within my AngularJS application. Despite stepping through the code in debuggers like Chrome or FF, the sessionStorage does not seem to be getting set. Below is the ...

Only 50% of the time does jQuery actually work

My webpage features two interactive buttons, the "liked" and "disliked" options. These buttons are represented by images attached to a link tag that triggers a database query when clicked. The outcome of this action is displayed in a #Messages section whic ...