Keeping JS changes on DOM after refresh - javascript

So, I have this weird thing going on in my test site, where I have every "link" (be it menu,button, or anything) to show/hide divs instead of loading pages. Pretty basic right? Except whenever I refresh the page, it all reverts back to the Homepage, which is expected. Based on my search for answers, I think I have to use the local/session storage option. Session sounds better.
So here's the deal. I looked up the w3schools page on sessionStorage and I get how it works, but I don't undestand how I could apply this to my page. Basically every link on my page runs a function that hides the previous div and shows a new one with the content. So I was thinking if every time a function triggered, it would store a value on a var that would appoint the function as the last used. Then somehow use sessionStorage and make it work, but I can't built it. Any help?
Here's a short example of my current code.
EDITED
var state = null;
function show1() {
state = "home";
"use strict";
document.getElementById('snow').style.display = "block";
document.getElementById('btn').style.display = "none";
}
function ramble() {
state = "ramble";
"use strict";
document.getElementById('ramble').style.display = "block";
document.getElementById('snow').style.display = "none";
document.getElementById('tex').style.display = "none";
}
That's basically it.Onclick show/hide.

You can use the following syntax:
Save data:
sessionStorage.setItem('key', 'value');
Retrieve data:
var data = sessionStorage.getItem('key');
More info and examples: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
The same goes with localStorage, but with the persistance differences you already found

I hope my solution will help you: If you want to keep your JS changes, you need to save them to database using AJAX and also change page architecture and logic to use data from database. After that, even if you reload page you will keep all your changes.

Related

Hiding an element by ID when in local storage once clicked not working

I am using this script to refresh the page after a button has been clicked and to hide that button once the ID (the shortcode) has been stored locally and to show a second element underneath:
function myVote(shortcode) {
$(document).on('submit', 'form', function() {
// Set product in local storage
localStorage.setItem(shortcode, "true");
// Refresh page after 3000 milliseconds
setTimeout(function() { location.reload(true); }, 3000);
});
};
</script>
<script>
for(let i=0; i<localStorage.length; i++) {
document.getElementById(localStorage.key(i)).style.display = "none";
}
</script>
The button has the following value: onClick="myVote('shortcode');"
The "shortcode" values are dynamic, each element has it's own.
I have built an upvoting system and the above means that once a vote has been placed they won't be able to vote for it again (unless they use another device or clear storage), the vote button is hidden and the "voted" button is now displayed. But for some reason, it's not working as it should and I'm struggling to figure it out. Check it out at https://www.carryr.com/vote.
At first, I thought I didn't configure the z-index for both of the element but they seem fine to me; the element underneath has a z-index of 11 and the one on top 100.
The SetTimeout may be the reason as after clicking on the said button, tahe page gets reload and localstorage value become null. Hence, the page throws document.getElementById(...) is null exception.
Please remove Timeout and retry the same.
You are storing many things in local storage which are not element ids.
So there will be an error when you try to access style property on an element that does not exist. Hence this code doesn't work.
Suggestion:
1.
const elm = document.getElementById(localstorage.key(i));
if (elm) {
elm.style.display="none"
}
2.It's better if you store the voted ids in a separate object and store it in storage. and read that object on load and style based on that.
// setting to storage
let voted = localStorage.getItem('voted');
if (!voted) {
voted = {};
} else {
voted = JSON.parse(voted);
}
voted.shortCode = true;
localStorage.setItem('voted',JSON.stringify(voted));
// reading from storage
voted = localStorage.getItem('voted');
if (!voted) {
voted = {}
} else {
voted = JSON.parse(voted);
}
Object.keys(voted).forEach(key => document.getElementById(key).style.display = 'none';
The above methods only store data in localstorage. so if user clears cache, opens a incognito window, opens in another system he won't be able to see the votes. better persist the state in a DB if possible

Storing a variable from an html document to display it in another

On the first page, the user is asked to select a name from a list (select/option tags) and click the "edit" button. User's choice is stored using the "option" variable and we redirect him/her to the next page.
When the body of the next page loads, it triggers the second function, which displays the option made previously as the main header of the page.
The problem is that, although onEdit() runs, displayOption() displays the variable as the empty string (as declared above the functions).
Why doesn't the second function "see" the alteration?
var option = "";
//"edit" button (onclick)
function onEdit() {
var selector = document.getElementById("selector");
option = selector.options[selector.selectedIndex].value;
window.location.href = "nextPage.html";
return false;
}
//"nextPage.html" body (onload)
function displayOption() {
var header = document.getElementById("header-main");
header.innerHTML = option;
}
Use local storage for that, it is easy to use and in this case highly appropriate.
See mdn docs
Example
on first page simply declare
localStorage.setItem('option', 'selectedOption');
on the second page get the var
var option = localStorage.getItem('option');
EDIT
as wendelin commented it is even more appropriate to use session storage, because it remove itself automatically.
The reason this doesn't work is that when nextPage.html loads, the entire script is re-evaluated, and option is now back to its default value of "".
You'll need another solution to persist the user's choice across refreshes. One of the more common approaches to something like this is to set the value as a query string parameter that can be read from within displayOption.

setting a variable in javascript to be used in another form

I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};

Variable Resets to 0 every refresh

I'm trying to make a code which lets me show how much a certain part of my website has been views.
My problem is, when I fresh refresh, it goes back to zero, instead of 2. I hope you can help me out. I want the code to run forever, or as long as I want it to, and it will just add a 1 to what it has been, even if it was yesterday. Here's the sample of the code.
<script type="text/javascript">
var bannerViews = 0;
function addViews (){
bannerViews = bannerViews + 1;
}
addViews();
</script>
<p>This banner has been viewed <script type="text/javascript">document.write(bannerViews);</script> timesĀ </p>
Hope you can help me out.
It is because every time you refresh your page, your code reinitializes. In-order to persist the data, you need to store it somewhere. Either in a cookie or a localstorage.
If you go ahead with the localstorage, here's how you do it.
var bannerViewCount = localStorage.getItem('bannerViews');
if(!bannerViewCount) {
bannerViewCount = 0;
}
function addViews() {
localStorage.setItem('bannerViews', ++bannerViewCount);
document.body.innerHTML = 'Banner view count is :' + bannerViewCount;
}
addViews();
Demo (click on Run on the top bar multiple times and see it incrementing)
Here, what am doing is first, fetching the banners view count. If I don't get it, I initialize it with zero.
Later, I on addViews() call, I increment the bannerViewCount by one and store it to the localStorage. That's it.
Note that the data is stored in your local storage, so if you are expecting that the count should be visible to other users too, you need to store it in a database or a text file and later parse it.
If you want to store it on the cloud, so that you can share the count across the visitors, you can do something like this.
function addViews() {
$.get('//jsonbin.io/b/5974382ca489d40388582791/latest', function(data) {
var bannerViewCount = data.bannerviews;
$.ajax({
url: '//jsonbin.io/b/update/5974382ca489d40388582791',
type: 'post',
dataType: 'json',
data: {
snippet: JSON.stringify({
bannerviews: ++data.bannerviews
})
},
success: function(fetch) {
var data = fetch.data;
document.body.innerHTML = 'Banner view count is : ' + JSON.parse(data).bannerviews;
}
});
});
}
addViews();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on "Run Code Snippet" button and see the counter incrementing. Go to any other browser and the count will persist as expected. Note that the data stored here can be manipulated as there is no authentication in place. So avoid it if you want the count to be precise and legit.
It goes back to 0 because the variable bannerViews is reinitialised to 0 on every page load.
You will need to store this variable in a JSON file/DB and fetch/update the value there.
Every time you refresh the page the code is going to be reset and variables are included.
To solve this you have to either use a web server and have the variable saved there or find a way to save the variable to the filesystem and load it
back.
The reason the counter is reset constantly is because you're declaring the variable during runtime. There is no persistence to the variable so every time the website is loaded, the variable starts against from 0. Each browser client would keep track of the variable separately so even if you were able to get the variable to persist on your local browser, you would not be able to keep track of the page views from other browsers. The solution to this problem is to keep track of the page views from a centralized server.
You can use a free service such as http://www.webestools.com/pages-views-counter-free-number-pages-views-statistics.html to create the counter that would persist between page views and different clients.
What you need to do is to get the initial value 0 , store in on the server , database or file.
change line var bannerViews = 0; to something like;
var bannerViews = getValueFromServer();
and every after re assigning it, you store it back to the external storage;
For now everytime you refersh the page .
the code var bannerViews = 0; will run and hence bannerViews will alwayz be re assigned to 0

Html local storage saving data

I have a simple main menu program.
HOW IT WORKS:
Simple, once you click level one and click on the done button, it unlocks level two, the problem is when you refresh the page it does not save it and level two is gone again.
Code I've tried:
I tried HTML Local storage, here are some examples I used
window.highestLevel = localStorage.getItem('highestLevel');
and stuff like that but I can't get it to save the level.
Please help here is a link. jsFiddle
Note: I want to use html local storage.
Save it with
window.localStorage.setItem('highestLevel', window.higestLevel);
Make sure you check that the browser you are working with supports localstorage. You could use Modernizr or something to do that easily.
To set something in localstorage:
javascript
localStorage.setItem('your-identifier', your-data);
So for example, to save a user's name:
javascript
localStorage.setItem('username', 'Luke Skywalker');
To get "username" back from localstorage:
javascript
localStorage.getItem('username');
Hope this helps!
You'll need to use getItem (as you did in your question) when you load the page, and hide level 2 as needed:
if (localStorage.getItem("highestLevel") <= 1) {
$("#level2").hide();
}
You'll also need to setItem to save when the user gets to level 2:
function mainMenuLvl2() {
localStorage.setItem("highestLevel", 2)
$('#level2').show();
}
Here's a JSFiddle: http://jsfiddle.net/ptcbkamx/2/
You can use localStorage and sessionStorage to store your data on client side like below
localStorage.setItem("variablename","value"); //--> this value is object type anything
var storedValue = localStorage.getItem("variablename");
or
sessionStorage.setItem("variablename","value");
var storedValue = sessionStorage.getItem("variablename");
You can use:
localStorage.setItem("highestLevel", window.highestLevel);
Then, if you want to get the highest level, use this:
localStorage.getItem("highestLevel", window.highestLevel);
I hope this helped!

Categories