Home > Software engineering >  Trying to switch between 4 stylesheets using a button and javascript
Trying to switch between 4 stylesheets using a button and javascript

Time:10-22

I have been looking around here, and found ways to toggle between 2 css files, but not more files than that. I need to use 1 button to alternate between 4 different files. My main css that is loaded with the html is called style1.css.

I found a js snippet that does this with images, and what it does is put all the images in an array, and take the first object out of and places it last in the array. I have been able to make this work:

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);
    }

Now, I tried remaking it for stylesheet files, but it fails:

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 did make sure that stylesheet id is 'styles'. Could somebody please show me where I go wrong?

CodePudding user response:

change src to href:

style.src = stylesUrl;

to

style.href = stylesUrl;

Full 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>

CodePudding user response:

initialize your stylesUrls out of your js class or use an index instead.

  • Related