Save after hiding a div

Asked

Viewed 156 times

1

I use a Jquery code to hide a div, and I would like when clicking close it to save and prevent it from being displayed again to the user when the page is reloaded.

$(document).ready(function() {
        $(".info-game--remove").click(function() {
            $('#info-game').css("display","none");
        });
});

I saw about cookies but do not know how to implement this code,

  • I’m not sure of the answer, but I believe that using localStorage is better and simpler than trying to use cookies. I have no experience with this so I can not offer more details, but the link should already help.

  • I’m building an example of using your case ;)

2 answers

2


You can use localStorage to store the information whether or not the button will appear.

The first thing is to leave the button natively hidden when loading the page:

<style>
#info-game{
    display: none;
}
</style>

When loading the page, you check whether the localStorage is empty -- if it is, you show the button, otherwise nothing will be done and the button will remain hidden:

$(document).ready(function() {

   if(!localStorage.infogame)  $('#info-game').show();

   $(".info-game--remove").click(function() {
      localStorage.infogame = "$('#info-game').hide()";
      eval(localStorage.infogame);
   });

});

Don’t forget to clean up the localStorage when you want to show the button again:

localStorage.removeItem('infogame');
  • thank you very much, that worked. :)

1

As you said yourself, you can do this with cookies:

$(document).ready(function() {
    $(".info-game--remove").click(function() {
        $('#info-game').css("display","none");
        document.cookie = "infoGameRemoved=true;"; 
    });
});

See this example in fiddle: Example cookie with Javascript

NOTE: To test, click on 'executar', then click on 'remover', then the cookie will be saved, click on 'executar' again and click on 'Mostre-me se #info-game está removido', whenever you click to run, it’s like giving a F5, see that if the cookie is true, it does not display, if it is changed to false, the div is displayed.

  • I put this code but it’s still showing the div when it recharges, am I doing it right?

Browser other questions tagged

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