Random site theme with change every 30 minutes

3

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 (which is standard), but if this same user comes back in 30 minutes he should see the site in one of the other two Orange or Green colors.

I'm not a programmer but with a lot of effort and stuffing some friends I got the code below that is partially working.

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

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

<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">

<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>
    
asked by anonymous 31.08.2015 / 01:59

1 answer

1

Well, from what I understood from the code you posted, you have 3 different .css files, and you're trying to randomize which one's going to 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, 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, except that, as I understand it, its randomization does not take into account css that was applied before the cookie expires will be excluded from the next randomization. That is, you can end up swapping out, after 30 minutes, arquivo1.css by arquivo1.css !

So I'll base my answer on an instantaneous randomization , not every 30 minutes as you requested in the comments. If you accept it, it may be interesting to edit the question. My answer will also not take into account the checking of css previous.

I'll give you two solutions: one by changing href of tag <link> , according to your code, and another by changing the <body> tag class, which I find most interesting since you can concentrate all your css in a single file.

  • Changing <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 have concluded (and I assume as truth from now on) that your .css files have the names

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

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

    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 loads, one of the 3 files is loaded together. It is worth remembering 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.

  • Changing the tag class <body>

    I find this option a bit more valid, since you would only have one .css file to keep. Assuming you have classes of type

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

    That you control your background color, for example, and that the rest of your theme cascades from them (ie, the h1 selector for .tema-1 would .tema-1 h1{} , and so on, you 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 operation on this pen . The background color changes each time you do a reload, and the color of the <h1> text changes as well, depending on the theme.

  • EDIT

    I managed to get 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 (ie, change arquivo1.css to arquivo1.css .

    Basically, I create two cookies : the first, called last , stores a reference to which was the last file that was created. The second, named css , is set to true and has a validity of 30 minutes. When it ceases to exist, I use the value stored in last to ensure that it is not the next one to be created. I did a few tests, and it seems to me that everything is correct. See if the code answers and let me know. Solution in pure JavaScript

    EDIT 2

    The cookie that controlled the expiration of time had to be recreated. I've created a method that does just that. See the 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();
    
    };
    
        
    02.09.2015 / 21:52