Daouda
Daouda

Reputation: 111

Persisting data on the page on refresh

I want to keep the data of the target ordered list before page refresh and then prepend it using jquery on document ready. Here is my code

// if an refresh event is fired
window.onbeforeunload = function(event){
  //store the messages into sessionStorage
  sessionStorage.setItem('ol', jQuery('#messages'));
  return undefined;
};
$(document).ready(function(){
  if (sessionStorage.getItem('ol')) {
  // Restore the contents of the ol (message contents)
    var ol = sessionStorage.getItem('ol');
    jQuery('#messages').html(ol);
  }
});
<div class="chat__main">

    <ol id="messages" class="chat__messages"></ol>

    <div class="chat__footer">
      <form id="message-form" action="">
        <input type="text" name="message" placeholder="Message" autofocus autocomplete="off"/>
        <button>Send</button>
      </form>
      <button id="send-location"> Send location</button>
    </div>
  </div>

But the code is not working as expected after refreshing the result is enter image description here

Although before refreshing it was enter image description here

Upvotes: 0

Views: 1157

Answers (2)

Daouda
Daouda

Reputation: 111

Thanks @charlietfl Here is what works for me

// if an refresh event is fired
window.onbeforeunload = function(event){
  //store the messages into sessionStorage
  sessionStorage.setItem('ol', jQuery('#messages').html());
  return undefined;
};
$(document).ready(function(){
  if (sessionStorage.getItem('ol')) {
  // Restore the contents of the ol (message contents)
    var ol = sessionStorage.getItem('ol');
    jQuery('#messages').html(ol);
  }
});

Upvotes: 0

sumeet kumar
sumeet kumar

Reputation: 2648

You need to use localStorage As data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.

More details on this link https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Upvotes: 1

Related Questions