javascript – Random website theme with change every 30min

Question:

I need my site to change the theme randomly every 30 min. So the logic would be:

User enters the site now and sees it in blue color (which is the default), but if this same user comes back in 30 minutes he should see the site in one of the other two colors Orange or Green.

I'm not a programmer but with a lot of effort and pissing off some friends I managed to get to the code below that is partially working.

It changes the site color every X time until OK, but the problem is that whenever the user returns to the site he sees it in the default blue color.

Does anyone know how to solve this last and important part? Thank you in advance for your help.

<link id="bones-stylesheet-css" href="http://www.mople.com.br/wp-content/themes/mople/library/css/mople-theme-1.css" type="text/css" media="all">

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/library/js/jquery.cookie.js" ></script>

<script>
            setInterval(function (onload) {
                if ($.cookie("css") !== null) {
                    console.log('cookie existe');
                    $("#bones-stylesheet-css").attr("href", $.cookie("css"));
                }
                else {
                    console.log('cookie expirou');
                    var random = Math.floor((Math.random() * 3) + 1) - 1;

                    var styleSheet = $(".bt-theme button").eq(random).attr("rel");

                    $.cookie("css", styleSheet, { expires: 1 / 100, path: '/' });
                    $("#bones-stylesheet-css").attr("href", $.cookie("css"));
                }

                console.log($("#bones-stylesheet-css").attr("href"));
            }, 10000);
        </script>

Answer:

Well, from what I understand from the code you posted, you have 3 different .css files, and you're trying to randomize which one will be loaded and used by the page. As I suggested in the comments, it might be smarter to do this randomization every time the user enters the page, and not necessarily every 30 minutes. Saving this time can be done with cookies or localStorage (this is speaking exclusively on the client side) but an anonymous session can already break the logic, besides, as I understand, its randomization does not take into account the css that was applied before the cookie expires will be deleted from the next randomization. In other words, you might end up replacing, after 30 minutes, the arquivo1.css with the arquivo1.css !

So I'm going to base my answer on instant randomization , not every 30 minutes as you asked in the comments. If you accept it, you might want to edit the question. My answer will also not take into account the verification of the previous css .

I'll give you two solutions: One changing the href of the <link> tag, according to your code, and the other changing the class of the <body> tag, which I think is more interesting, because you can concentrate all your css in a single file.

  1. Changing the <href>

    According to this line

     <link rel="stylesheet" id="bones-stylesheet-css" href="http://www.mople.com.br/wp-content/themes/mople/library/css/mople-theme-1.css" type="text/css" media="all">

    I've come to the conclusion (and I'll assume it's true from now on) that your .css files have the names

     mople-theme-1.css mople-theme-2.css mople-theme-3.css

    With pure javascript , you can create the .css file like this:

     var _random = Math.floor((Math.random() * 3) + 1); var _href = 'http://www.mople.com.br/wp-content/themes/mople/library/css/mople-theme-' + _random + '.css'; var _link = document.createElement('link'); _link.setAttribute('rel', 'stylesheet'); _link.setAttribute('type', 'text/css'); _link.setAttribute('href', _href); var _head = document.getElementsByTagName('head')[0]; _head.appendChild(_link);

    This causes, each time the page is loaded, one of the 3 files is loaded together. Remember that this does not guarantee that every time it will be a different file, it only guarantees that it will be one of the 3.

  2. Changing the class of the <body> tag

    I find this option a little more valid since you would only have one .css file to keep. Assuming you have classes like

     .tema-1{} .tema-2{} .tema-3{}

    Let them control your background color, for example, and let everything else in your theme cascade from them (ie, the h1 selector for .tema-1 would be .tema-1 h1{} , and so on, you can add the class to the <body> tag randomly, in a similar way to the previous example. Using pure javascript

     var _random = Math.floor((Math.random() * 3) + 1); var _body = document.getElementsByTagName('html')[0]; _body.className = 'tema-' + _random;

    You can see a basic example of this working on this pen . The background color changes each time you reload, and the <h1> text color changes as well, depending on the theme.

EDIT

I managed to arrive at a solution where every 30 minutes, the .css file that will be loaded is different, ensuring that it will not be the same as the previous one (that is, changing the arquivo1.css by arquivo1.css .

Basically, I create two cookies : the first one, called last , keeps a reference to which was the last file that was created. The second, called css , receives the value true and has a validity of 30 minutes. When it no longer exists, I use the value stored in last to ensure it isn't the next one to be created. I did a few tests, and it looks like everything is fine. See if the code suits you and let me know. Solution in pure JavaScript

EDIT 2

It remained to recreate the cookie that controlled the expiration of time. I created a method that does just that. See changed code

function getCookie(cname) { //método retirado do site da W3C
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return null;
}

function createStylesheet(_file){
    var _href = 'http://www.mople.com.br/wp-content/themes/mople/library/css/' + _file + '.css';
    var _link = document.createElement('link');
    _link.setAttribute('rel', 'stylesheet');
    _link.setAttribute('type', 'text/css');
    _link.setAttribute('href', _href);
    var _head = document.getElementsByTagName('head')[0];
    _head.appendChild(_link);

    document.cookie = "last=" + _file; //cria um cookie dizendo qual foi o ultimo css
}

function createExpireCookie(){
    var _date = new Date();
    _date.setTime(_date.getTime()+(30*60*1000));

    var _expires = ";expires=" + _date.toUTCString();
    document.cookie = "css=true"+ _expires; //cria cookie com validade de 30 minutos 
}

if(null == getCookie('last')){ //nao existe cookie do ultimo arquivo
    createStylesheet('mople-theme-1');
    createExpireCookie();
} 
else if (null == getCookie('css')){ //existe cookie referente ao ultimo css, mas já se passaram 30 minutos
    var _sheets = ['mople-theme-1', 'mople-theme-2', 'mople-theme-3']; //possíveis arquivos
    var _index = _sheets.indexOf(getCookie('last'));

    _sheets.splice(_index, 1);  //remove o ultimo do array de possibilidades

    createStylesheet(_sheets[Math.floor(Math.random()*_sheets.length)]); //cria um css randomizando as possibilidades do array
    createExpireCookie();

};
Scroll to Top