How do I switch between 2 style sheets?

1

Well, I have a site that all its color is gold and black . Some font colors in gold, then golden, gold sidebar, etc ...

How do I, when I put a button on the side of my site, written "purple version", and the visitor clicks this button, change this CSS and replace with a new CSS that I will have created, in a version of the entire site in the "purple" color.

As if the site had 2 color styles, and the visitor could choose which color he wants to browse the site.

    
asked by anonymous 10.11.2017 / 05:31

1 answer

1

You can use the jquery .attr("href") command with the .on("click") command on the button to change the link in your css.

Here's an example I made below, where I created two links one to change my theme from golden to purple, and another to change the theme to blue.

index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link id="temacss" href="temadourado.css" rel="stylesheet" type="text/css"/> 
</head>

<body>

<div id="quadrado">Bla bla bla</div>

<a href="temaroxo.css" class="trocacssbtn">Trocar para Roxo</a>
<a href="temaazul.css" class="trocacssbtn">Trocar para Azul</a>


<script type="text/javascript" src="jquery-3.2.1.min.js"></script>

<script>
$(document).ready(function() {
    // Ao pressionar qualquer link ou botão que contém
    // a class "trocacssbtn", executar a função.
    $(".trocacssbtn").on("click", function() {

    // Pega o atributo do link clicado para definir qual será o valor a ser trocado.
        var cssclass = $(this).attr("href"); 

       // Faz a troca do arquivo de css tema
       $("#temacss").attr("href", cssclass);

       // Retorna false para manter na mesma tela e finalizar a função.
        return false;
    });
});
</script>
</body>
</html>

temadourado.css

div#quadrado {
    width: 500px;
    height: 500px;
    background-color: #ff9600;
}

temaroxo.css

div#quadrado {
    width: 500px;
    height: 500px;
    background-color: #783486;
}

temaazul.css

div#quadrado {
    width: 500px;
    height: 500px;
    background-color: #072794;
}

The only thing you need to think about next is how you want to fix it. The user will change when clicking, but if the page refresh will return everything original.

So you have to see in your usage, what better way to update and keep the changes. There are people who use cookies, others save the preferences in the database in the user's registry. There it is with you.

    
10.11.2017 / 07:10