How do you "memorize" an action on a website?

Asked

Viewed 48 times

2

I want to put in my blog, the possibility of changing his theme (background/color), for CSS and Javascript. But I would love to be able to "memorize" this action, so that whenever the user re-enters, the theme is in the last one he chose (until somehow it clears this data, of course). I don’t understand this thing but I imagine it is very complex. Can you explain briefly how it works? And if it’s not that complex, you can tell me what to do?

  • 1

    You could launch to the server to save what was the style that the user preferred, resulting then that he would access it in the favorite way in any browser... or you could save the choice as a cookie or something worth it (storage Sqlite if I’m not mistaken is possible) using JS. This second alternative would only maintain the user’s preference in the browser in which this choice was made, however. And to properly consume the site would need to have a script that would treat these cookies to send the appropriate files

  • This second option is more appropriate, since I don’t have a login system there. I’ll do a little more research on this tip of yours

  • good research. Do not forget, if you can find the appropriate answer, post it here. I understand the theory of what should be done, but I have no idea how to do it. Answering here you would help us all, including yourself

  • Okay, I’ll do it!

  • @Jeffersonquesado tried to muuuuito that I am already exhausted... On the Internet I found demonstrations that worked perfectly, but they are different from the way I wanted/needed and I couldn’t relate to their logic to make mine work. One of which worked makes a flicker of the original style for a few seconds before changing (horrible), another works very well but does not let have a standard background (what is the logic?!). Another is perfect but the user would have to type the color he wants for an input, it can’t be like this..

  • Anyway... if you have any tips I’ll thank you. And I can also send you some links of demos, if you want to take a look. Now I think I’ll post one of them here in the O.R..

  • My knowledge unfortunately limited me to my previous comments. I am sad that your search was not fruitful enough =( I thought that the two answers could have helped you... or maybe the help came and didn’t notice. It happens, it’s frustrating, but doing what? I, a bachelor in computer science for about 5 years, I still had to watch and read and ask about functional programming to begin to understand a little that is </vent> Anyway, when you have 20 points of reputation you can chat [...]

  • [...] There you can chat head-to-head with the staff, including better trained people on the web. I only ask to be patient and continue studying and collaborating =) Sometimes the answers take a long time to come, sometimes it takes a long time to understand too. Don’t let a stumble keep you from going forward

Show 3 more comments

2 answers

2

You can use the Web Storage (HTML5):

Example:

// Guardar
localStorage.setItem("cor_css", "vermelho");
// Obter (aí você precisa moldar esta info recebida e aplicar nos objetos que você deseja
document.getElementById("result").innerHTML = localStorage.getItem("cor_css");
  • Wow, I just saw that answer. Ali in "cor_css" would be the name of my function with the set of styles?

  • @Kenyajj cor_css is an item that retains a value. I put "red" but it may be a set of information in your case ;)

1

Assuming that you provide different themes for the user to "customize/choose" to apply different styles in the UI of your site, you can use localStorage() or cookies, both solutions use javascript and can be modified or deleted by the user on the front end whether using the developer’s console or tools, whether using plugins or even going to settings and clearing the data in the browser settings or even you can create a function to "clean" these settings.

Example using localStorage():

<!-- IN HEAD -->
<link id="css-template-link" rel="stylesheet" href="default-template.css">

<!-- IN BODY -->
<select id="select-css-template">
   <option value="default">Dedault Template</option>
   <option value="dark">Dark Template</option>
   <option value="cyan">Cyan Template</option>
   <option value="ice">Ice Template</option>
</select

<script>
    let select = document.getElementById('select-css-template')
    select.addEventListener('change', function(evt) {
        let css = evt.options[evt.selectedIndex].value
        // apply
        let link = document.getElementById('css-template-link')
        link.href = css + '-template.css'
        // save to localStorage
        localStorage.setItem('css-template', css)
    }, false)

    // load
    if ( localStorage.getItem('css-template') ) {
        let css = localStorage.getItem('css-template')
        let link = document.getElementById('css-template-link')
        // apply
        link.href = css + '-template.css'
    }

    // clear: localStorage.removeItem('css-template')
</script>

Using localStorage() there is no default expiration time. A cookie border needs to set an expiration time, a function to search for a single entry in the values stored on document.cookie as well as a function to rewrite the values of a cookie (and also its expiration time) as well as to clear (set a negative time).

Example using document.cookie

<script>
    // request cookie approach
    let getCookie = name => {
        return document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + name.replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1") || false
    }
    // save cookie
    let saveToCookie = (name, value, expirationDays) => {
        let makeTime = t => {
            if ( typeof t === 'number' ) {
                let d = new Date()
                d.setMilliseconds(d.getMilliseconds() + t * 864e+5) // 864e+5 equal 1 day or 86400000 milliseconds
                return d.toString()
            }
        }
        document.cookie = name + '=' + value + '; expires= + makeTime(expirationDays) + '; path=/'
    }

    let select = document.getElementById('select-css-template')
    select.addEventListener('change', function(evt) {
        let css = evt.options[evt.selectedIndex].value
        // apply
        let link = document.getElementById('css-template-link')
        link.href = css + '-template.css'
        // save in cookie
        saveToCookie('css-template', css, 30) // 30 days of expiration
    }, false)

    // load
    if ( getCookie('css-template') ) {
        let css = getCookie('css-template')
        let link = document.getElementById('css-template-link')
        // apply
        link.href = getCookie('css-template') + '-template.css'
    }

    // clear: saveToCookie('css-template', '', -1)
</script>

Clearing the cookie will not change the css back to default, but following logic it is easy to reset the link to the default css.

  • Thank you so much for the answer, super well explained! I will make a few attempts and come back here to tell if I had results and select the correct answer. =)

  • I came back... well, I tried very hard and I couldn’t... In this example I did not understand very well, but I read stories and more to see if I understood. Nothing. On the Internet I tested some examples that worked perfectly, but it’s far from the way I want it to work and in my particular case, I can’t make it work trying to understand the logic. One of them gives a flicker of the original style (ranging from 1 to 5 seconds) when the page is reloaded and gets very boring... The second one doesn’t allow you to already have background in css, you have to have nothing or it doesn’t work...

  • What example? with cookie or localStorage And what exactly don’t you understand? When a style sheet is first loaded yes, it takes a few seconds (depending on the connection speed) to load bad, after that it is cached and the next changes occur practically without perception (pq are already in the cache). If you want to "pre-store" style sheets so as not to "feel" this effect, then another story would have to use Service Worker

Browser other questions tagged

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