Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting DOM changes after clicking a link and then pressing the Back button

I'm using jQuery's appendTo() method to append items to an unordered list. When the user clicks another link, and then presses the Back button, the appended items disappear. Is there a way to persist those changes using JavaScript?

like image 783
ustun Avatar asked Aug 14 '11 17:08

ustun


2 Answers

When hitting BACK, some browsers cache te previous (originally loaded) page. If you can regenerate the page with a fresh reload you can use cache-control 'no-store, no-cache, must-revalidate' to force this on a BACK.

Chrome wants no-store, and IE wants must-revalidate. For other browsers (and w3c) no-cache is enough.

like image 76
woens Avatar answered Sep 27 '22 19:09

woens


Once your user navigates away from your page, the DOM is discarded. When your user hits the back button, they get a fresh copy of the HTML from your server (or from their cache).

So, you have one of 2 options:

  1. The correct way would be to save the DOM state in a cookie (or session), and then on page load check if that cookie is present, and if so, append that info.

  2. Since you have not provided enough information, I'm not exactly sure what you're trying to accomplish. So, if a cookie is not good enough, you might have to attach a click event to the link, and instead of just sending them off to that link, you'll first store the DOM in a variable var theDOM = $('html').clone(true);, and then load in the HTML for that link with an AJAX request.

You'll also have to inform the browser that your history state has changed. That can be accomplished with HTML5's new History API. In older browsers you can do something similar via the hash part of the URL (although in older versions of IE even that won't work). Then, when the user clicks the back button, you'll reload that DOM from your variable...

Either way, this is WAY too complicated. You're probably looking at this the wrong way. What are you trying to accomplish?

like image 22
Joseph Silber Avatar answered Sep 27 '22 18:09

Joseph Silber