Reputation: 543
I am trying to achieve what may look like a simple task but it is totally confusing me.
When the user clicks a menu item the page refreshes and the user ends up on another page.
A div gets updated with an updated text.
The problem I have is that when the page is refreshed I lose the message "You are on a new page", how do I keep the updated message on the new page?
jquery -
<script>
$(document).ready(function () {
$("li.sub-level").click(function (e) {
$('.mylink').html("You are on a new page");
});
});
</script>
html -
<div class="mylink">My link</div>
Upvotes: 1
Views: 2370
Reputation: 1896
You need to first "save" your first location in the infoObj, I suggest you do it with the url of the first page. This will prevent the string "You are on a new page" when you are on the first page.
$(document).ready(function() {
var infoObj = {};
var url = window.location.href;
if (localStorage.myLink != null) {
infoObj = JSON.parse(localStorage.myLink)
if (infoObj.url == url) {
$('.mylink').html(infoObj.text);
}
}
$("li.sub-level").click(function(e) {
infoObj = {
url: "PUT YOU FIRST PAGE URL HERE",
text: "You are on a new page"
}
localStorage.myLink = JSON.stringify(infoObj)
});
});
Upvotes: 1
Reputation: 220
I think you should visit this link. i hope you will get your answer.
Link is here Demo Link
Or user this below code. how sessionStorage works.
<script>
// Run on page load
window.onload = function() {
// If sessionStorage is storing default values (ex. name), exit the function and do not restore data
if (sessionStorage.getItem('name') == "name") {
return;
}
// If values are not blank, restore them to the fields
var name = sessionStorage.getItem('name');
if (name !== null) $('#inputName').val(name);
var email = sessionStorage.getItem('email');
if (email !== null) $('#inputEmail').val(email);
var subject= sessionStorage.getItem('subject');
if (subject!== null) $('#inputSubject').val(subject);
var message= sessionStorage.getItem('message');
if (message!== null) $('#inputMessage').val(message);
}
// Before refreshing the page, save the form data to sessionStorage
window.onbeforeunload = function() {
sessionStorage.setItem("name", $('#inputName').val());
sessionStorage.setItem("email", $('#inputEmail').val());
sessionStorage.setItem("subject", $('#inputSubject').val());
sessionStorage.setItem("message", $('#inputMessage').val());
}
</script>
Upvotes: 0