Store "do not show again" with localStorage

Asked

Viewed 82 times

1

I have a div which can be hidden by clicking a button:

$(".fechar").click(function(){
    $("#mensagem").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mensagem">
  <p>(...)</p>
  <button class="fechar">Fechar e não mostrar novamente</button>
</div>

What I need is for her not to appear again after being hidden for the first time.

I found a way with the Jquery dialog, but it does not allow me to customize right, at least not in a simple way, so I need and I prefer it to be like this.

How do I memorize this action in localStorage?

  • But this code you put in already does just that.

  • No, @Leandrade... I need it to be memorized in localStorage so that even if you refresh the page, this div won’t appear again...

  • @Thiagosoubra, see my answer on

  • Our truth, I didn’t pay attention!

1 answer

0


Simple, first you need to capture in your event click that the div was clicked, could be something like:

$(".fechar").click(function(){
    $("#mensagem").hide();
    //definindo que foi clicado
    window.localStorage.setItem('clicado', 'clicado');
});

And in his document.ready(), check whether clicado is set, if you are, hide the div:

$(document).ready(function(){ 
   if(window.localStorage.getItem('clicado')) {
        $("#mensagem").hide(); 
   } 
});

Your final code:

$(".fechar").click(function(){
    $("#mensagem").hide();
    window.localStorage.setItem('clicado', 'clicado');
});

$(document).ready(function(){ 
   if(window.localStorage.getItem('clicado')) {
        $("#mensagem").hide(); 
        console.log('clicado definido')
   } 
});

See working on Jsfiddle: https://jsfiddle.net/x43n7fsu/2/

  • Thank you so much for the answer, friend! But I got a little lost... I pasted this code there and the function didn’t work. It must be because I don’t know how to use it. I wonder if you can put for me here in this Fiddle? link

  • @Thiagosoubra I edited the answer, look now.

  • Perfect! very grateful!!

  • Not at all, buddy :D

Browser other questions tagged

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