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>


<div id="changeColor">
    
    <button class="default" >Change to default</button>
    <button class="black" >Change to black</button>
    <button class="red" >Change to red</button>
    <button class="blue" >Change to blue</button>

</div>

CSS

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

html.red { background: green; }


#changeColor .current {
    background: yellow;
}

JavaScript

(function($) {
  $.fn.styleSwitch = function( options ) {

    var objP = this.parent();
      
    return this.each(function() {
        
        var obj = $(this),
            objS = obj.siblings(),
            eHtml = $('html'),
            o = $.extend( {}, $.fn.styleSwitch.defaults, options );
        
            // We use this to check if a cookie is set, and this is
            // also used to pass the class as an id to the <html> element.
            swCookie = $.cookie( 'styleSwitch' );

        // When document is ready, if style was once switched, use the stored style.
        // - Give new id to body corresponding the set cookie.
        // - Cookie value will the uttons class that was last clicked, or by default = null.
        if ( swCookie ) {
        
            changeStyle( swCookie );
            markCurrent( swCookie );
        
        }
        
        // On click:
        // - Get class from clicked element.
        // - Give new id to <html> corresponding the class in the clicked button.
        // - Set cookie as the clicked elements class.
        obj.on('click', function( e ) {
        
            var myClass = $(this).attr("class");
            
            if ( myClass === 'default' ) {
                defaultStyle();
            }
            else {
                changeStyle( myClass );
            }

            markCurrent( e, myClass );
            $.cookie( 'styleSwitch', myClass );
        
            o.click.call(this);
            
        });
        
        function defaultStyle() {
            eHtml.attr( 'id','' );
            $.removeCookie( 'styleSwitch' );
        }
        
        // Gives new id to <html> corresponding either the 
        // set cookie, or the class in the clicked button.
        function changeStyle( myStyle ) {
            
            eHtml.attr( 'id', myStyle );
            
        }

        function markCurrent( e, myStyle ) {
            
            if ( e.type === 'click' ) {
       ...