JSFiddle - React, Tailwind, and code Playground

by lollero

HTML

<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>

<button class="style-black" >Change to black</button>
<button class="style-red" >Change to red</button>
asdasd
<button class="style-blue" >Change to blue</button>

CSS

#black { background: black; }
#red { background: red; }
#blue { background: blue; }

JavaScript

(function( $ ){
        
    var obj = $('button[class^="style-"]');
    
    // Store cookie so that we can use it to check if 
    // cookie is set, and also to place the right color.
    var sCookie = $.cookie( 'styleCookie' );
    
    // When document is ready, if a color is set via cookies, use it.
    // - Give new id to body corresponding the set cookie.
    // ( Cookie value will be the color in the buttons class that was last clicked, or by default = null. )
    if ( sCookie ) {
    
        changeStyle( sCookie );
    
    }
    
    // On click:
    // - Get class from clicked element and remove "style-" from it.
    // - Give new id to body corresponding the class in the clicked button.
    // - Set cookie as the clicked elements class.
    obj.on('click', function() {
    
        var myColor = $(this).attr("class").replace('style-', '');
    
        changeStyle( myColor );
        $.cookie( 'styleCookie', myColor );
        
    });
    
    // Gives new id to body corresponding either the 
    // set cookie, or the class in the clicked button.
    function changeStyle( color ) {
        $('html').attr( "id", color );
    }

})( jQuery );