Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change two buttons into one (toggle)

Tags:

javascript

I have this code, which swich 2 different external .css after click on one of two buttons and it works fine, but I need to change it and make only one button with toggling between these two .css files. Thank you

<script type="text/javascript">

    function changeCSS(cssFile, cssLinkIndex) {

    var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

    var newlink = document.createElement("link")
    newlink.setAttribute("rel", "stylesheet");
    newlink.setAttribute("type", "text/css");
    newlink.setAttribute("href", cssFile);

    document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
  }
</script>

<a href="#" onclick="changeCSS('css/main.css', 1);">STYLE 1</a>
<a href="#" onclick="changeCSS('css/main2.css', 1);">STYLE 2</a>
<div class="box">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>
like image 746
culter Avatar asked Feb 21 '26 06:02

culter


1 Answers

var cssFiles = ['css/main.css', 'css/main2.css'];
var currentFile = 0;

function changeCSS(cssLinkIndex) {

    if(currentFile + 1 < cssFiles.length) currentFile++;
    else currentFile = 0;

    var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

    var newlink = document.createElement("link")
    newlink.setAttribute("rel", "stylesheet");
    newlink.setAttribute("type", "text/css");
    newlink.setAttribute("href", cssFiles[currentFile]);

    document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}

You can then call that like this:

<a href="#" onclick="changeCSS(1);">CHANGE STYLE</a>

It simply maintains a counter that is incremented each time the button is clicked, to point to a different index of an array containing the names of your stylesheets. If the counter reaches the maximum, it wraps around to 0 and starts again.

like image 186
James Allardice Avatar answered Feb 22 '26 21:02

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!