Question

I have got Javascript function to show content if you click on <div id = button1/2/3>. But after refreshing the page, all is hidden. I would like to remember last action - cache it.

Please, help.

        $(document).ready(function() {
          $("#button1, #button2, #button3").hide();

          $("#news1").click(function() {
          $("#button1").show(); 
          $("#button2, #button3").hide();
          });

          $("#news2").click(function() {
          $("#button2").show(); 
          $("#button1, #button3").hide();
          });

          $("#news3").click(function() {
          $("#button3").show(); 
          $("#button1, #button2").hide();
          });
       });
Was it helpful?

Solution

You can use locastorage for that. localstorage will persist in between http calls. So you will be able to persist the state easily. I have updated your code also to follow best practises also.

Here goes the HTML :

<input id="button1" type="button" class="expand" value="b1">
<input id="button2" type="button" class="expand" value="b2">
<input id="button3" type="button" class="expand" value="b3">


<input class="news" type="button" data-id="1" value="n1">
<input class="news" type="button" data-id="2" value="n2">
<input class="news" type="button" data-id="3" value="n3">

Here is the javascript. Please follow that i have used classes in the most of the cases :

    (function () {

        function resetLocalStorage() {
            $('.expand').each(function () {
                delete localStorage[$(this).attr('id')];
            });
        }

        $(".expand").each(function () {
            if (localStorage.hasOwnProperty($(this).attr('id'))) $(this).show();
            else if (localStorage.hasOwnProperty('trackingIsOn')) $(this).hide();
        });

        $(".news").click(function () {
            $('.expand').hide();
            var buttonElem = $('#button' + $(this).data('id'));
            buttonElem.show();
            resetLocalStorage();
            localStorage[buttonElem.attr('id')] = true;
            localStorage.trackingIsOn = true;
        });

    })();

You can find the full working example here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top