Random site theme with exchange every 30min

Asked

Viewed 222 times

3

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

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

I am not a programmer but with a lot of effort and annoying some friends I managed to get to the code below that is partially working.

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

Does anyone know how to solve this last and important part? Thanks in advance for the 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>
  • One problem is that its function is running every 10 seconds, but not when the site is loaded. Then for up to 10 seconds the site can stay in the default theme. Is this cookie not being written elsewhere?

  • I put 10 sec to be able to view the CSS exchange without having to wait 30 min. But even increasing to any other time the problem continues.

  • Yes, precisely because the first time will take the time you put in to run. setInterval() does not run the first time immediately. The blue theme should be the default that comes from the server, correct? On a server with Javascript turned off, the default would be blue?

  • Yes blue is the default. Is it right to put a variable in place of the CSS path? Yeah, I thought about going this way but I don’t know how to get there.

  • Try the following: move all Function (onload) { ... } code to a function, call the function inside setInterval(), and also call the function then so that it runs immediately when loading. Maybe resolav.

  • I know it’s part of the question, but you has to make this change every 30 minutes, necessarily? Voce could not simply randomize the color every time the user enters, regardless of the time? it would facilitate a bit

  • Hi Caio I haven’t tried the @epx option yet (it will probably give some simple error that I won’t be able to solve) but I can go this way instead of always leaving random. What the code would look like?

  • @Petersonramos, I’m building an answer

Show 3 more comments

1 answer

1

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

Therefore, I will base my response on an instant randomization, and not every 30 minutes, as you asked in the comments. If you accept it, it may be interesting to edit the question. Nor will my reply take account of the css previous.

I will give two solutions: One changing the href tag <link>, according to your code, and another changing the tag class <body>, which I find most interesting because you can concentrate all your css in a single file.

  1. Altering 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 have drawn the conclusion (and I assume it to be true from now on) that your files .css has the names

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

    With javascript pure, you can create the file .css in that 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 one of the 3 files to be loaded together each time the page is loaded. Remember that this does not guarantee that every time will be a different file, just ensures that it will be one of the 3.

  2. Changing the tag class <body>

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

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

    That they control their background color, for example, and that all the rest of their theme cascades from them (i.e., the dial h1 to the .tema-1 would be .tema-1 h1{}, and so on, you can add the class to the tag <body> randomly, in a manner similar 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 that flash drive. The background color changes each time you do a Reload, and the text color of the <h1> also changes, according to the theme.

EDIT

I managed to reach a solution where every 30 minutes, the file .css which will be loaded is different, ensuring that it will not be the same as the previous one (ie arquivo1.css for arquivo1.css.

Basically, I create two cookies: the first, called last, keeps a reference to which was the last file that was created. The second, named css, receives the amount true and has a shelf life 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 have done a few tests, and it seems to me that everything is correct. See if the code meets you and let me know. Solution in pure Javascript

EDIT 2

We had to recreate the cookie that controlled the expiration of time. I created a method that does just that. Look at 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();

};
  • Hi Caio, for me the best option is the first because as I am working with Less it was much easier to separate CSS in 3 sheets.

  • Hi Caio, for me the best option is the first because as I am working with Less it was much easier to separate CSS into 3 sheets. Because all I had to do was separate the variable.scss file and call out all the colors over there. Thank you so much for the help and your code worked 90% the only problem I still have is that every page change the site is changing color. I tried to solve this with window.sessionStorage, because after what you said about the cookie I thought it was the best way, but no luck. Do you have any suggestions to resolve this last point?

  • Thank you Caio I will test tonight and give you a feedback

  • Hi Caio, unfortunately did not work the color of the site changes every refresh or enter the room. Any suggestions

  • @Petersonramos ta there

  • Hi Caio, unfortunately did not work the color of the site changes every refresh or enter some page. Any suggestions?

  • @Petersonramos here is working all right, including with reference to your files .css.

  • Hi @caio-Felipe-Pereira, sorry for the delay in answering the code yes it works but there is a small problem. CSS is added to the page by JS, and after it is loaded everything is stored inside the Cookie as it should be. But when we move to the other page it checks that the Cookie exists and then does not run the JS and as it is who applies the CSS it is without style. When we put a lifespan of a few seconds in the Cookie to test everything is ok, but for longer times the problem appears.

  • I realized the problem because everything started OK and suddenly when browsing the pages lost the style. I applied an Alert to the JS to check what variables were returning and it also stopped working overnight. Then, I noticed that when cleaning the Cookie from the browser everything was working again, CSS was applied and Alert pipocava on the screen with the value of variables. This concludes that once the Cookie is generated the browser no longer runs the JS and does not apply the CSS. Do you have any suggestions for this last problem?

  • Dear I want to thank you immensely for your help, and if you ever need help on design, usability, information architecture and CSS for desktop or mobile I am available to help you.

  • @Petersonramos, then everything depends on how you call this Javascript internally on your pages will create a .css whenever called. you can reuse it as you see fit

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.