1

I have made a simple function that shows some content if you press a specific button. My problem is just that I don't know how to save that action even if you reload the page.

Here is my HTML:

<div class="content1" style="display: none;">
  <p style="color: green;">Some content from content1</p>
</div>

<div class="content2" style="display: none;">
  <p style="color: red;">Some content from content2</p>
</div>


<button class="content1-btn">Button 1</button>

<button class="content2-btn">Button 2</button>

Here is my jQuery:

$(document).ready(function(){
  $(".content1-btn").click(function(){
    $(".content1").show();
  });
  $(".content2-btn").click(function(){
    $(".content2").show();
  });
});

The above code works well enough as it should. The problem is that I want a cookie to remember witch button you have clicked on. If for example you click button 1, then .content1 should still be displayed even if you reload the page. I hope it makes sense.

Oscar S.
  • 49
  • 4
  • 1
    Try [`localstorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) for storing data... – vaku Jun 07 '19 at 09:25
  • did you tried `localStorage` – Udhay Titus Jun 07 '19 at 09:25
  • There are lots of questions about this, for example: https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery. Have you done any research at all? If so, please edit the question to show the code that you tried. – Rory McCrossan Jun 07 '19 at 09:26
  • You should probably not store which button is clicked, but what state should the application be in. Then, you can store this state in e.g. the localStorage. Next time, you open the application, you'll read the state and rebuild the web app from there (show the necessary content). You can also misuse a cookie for that. – ssc-hrep3 Jun 07 '19 at 09:42

1 Answers1

1

try to use localstorage it will works or try this,

  $(".content1-btn").click(function(){
    $(".content2").hide();
    $(".content1").show();
    localStorage.setItem('buttonClicked', '.content1');
  });
  $(".content2-btn").click(function(){
  $(".content1").hide();
    $(".content2").show();
    localStorage.setItem('buttonClicked', '.content2');
  });
  
  $(document).ready(function(){
  $(".content2, .content1").hide();
   var val = localStorage.getItem('buttonClicked');
    $(val).show();
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content1" style="display: none;">
  <p style="color: green;">Some content from content1</p>
</div>

<div class="content2" style="display: none;">
  <p style="color: red;">Some content from content2</p>
</div>


<button class="content1-btn">Button 1</button>

<button class="content2-btn">Button 2</button>

Check this fiddle

Udhay Titus
  • 5,480
  • 4
  • 21
  • 39