Saving $("#some-id") in a variable to access it later - javascript

I want to save selected jQuery object to some variable and to be able to access it after navigating to some other page, since after reloading it disappears.
Here is what I am trying to do:
var active_accordion;
$(function() {
active_accordion.prop('checked', true);
$('.active-evm a').on('click', function() {
active_accordion = $('#section-1');
alert(active_accordion);
});
}
Whenever link is clicked I save $('#section-1') to active_accordion, and after navigating to other page I try to change property checked to true.
Of course it doesn't work, because active_accordion disappears after navigation. So where can I store it?

save to local storage,
the example,
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

You can store it in session storage sessionStorage.
sessionStorage.setItem("itemKey", value);
Edit: sessionStorage items persist as long as the browser session is active.
If you want to persist your items even if you restart your browser, you can use localStorage, but be careful with its usage as the data tends to get stale if you do not use it properly.

There are lot of ways you can do this
1) Store those in session
2) Store it on cookies
Note :when using Cookies be careful, don't put too much in them (I
think there is a limit at 4kb).
3) you can store it in local storage in your system
example : save values to a file
4) you can store it on database
5) Or just use PersistJS
PersistJS is good choice because you can store large objects like
window objects aswell
6) You can use the help of WebStorage
7)you can use window.name
it is originated before localStorage/sessionStorage, you can store information in the window.name property:
window.name = "stringvalue"
It can only store strings
, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ object });

Related

How I can call dynamically an object over html in javascript

I have a dropdown menu in one html page and when I choose one option of this dropdown menu I link with href to another html page. In this html page I want to console.log some particular specifics of the option that I have chose(the specifics are javascript objects).
My question is how I can make this dynamically? To be more clear thing an analogy, I have a dropdown menu with fruits I choose orange, I href in orange.html and in this page I want to console the javascript object fruit.orange but I want this to be dynamically not static(just writing in orange.html fruit.orange because I know that I am in orange.html)
Is this feasible?
I hope my question is clear and not ambiguous
By clicking on the option you need to store it so that on a new page you can find out which option was chosen. If you don't want to use a server that allows you to move the variable from one view to another, then you can use localStorage to save the variable.
Adding some data to localStorage is as easy as using the setItem()
method. I'll use a generic key and value for the names, but they can
be any strings.
localStorage.setItem('key', 'value')
If you want to get the value for a particular key, you'll use the
getItem() method.
localStorage.getItem('key')
Source: https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
If you want the saved information to be automatically deleted once the browser is closed, you can use sessionStorage instead
sessionStorage is similar to localStorage; the difference is that
while data in localStorage doesn't expire, data in sessionStorage is
cleared when the page session ends.
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key');
// Remove all saved data from sessionStorage
sessionStorage.clear();
Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Depending on how complex the object is, it's unwieldy to pass it through the form, which would leave you with the option of storing it via local storage, or grabbing it via AJAX. I would go with the latter, however this would essentially mean doing what you said you don't want to do, i.e. recognizing something about the orange.html page and making the call. To be clearer, this is something like what I would do:
On orange.html have an AJAX call:
let xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = () => {
if(this.readyState == 4 && this.status == 200) {
let obj = this.responseText;
}
}
xhttp.open("GET", "orange.js", true)
xhttp.send()
Of course if you have a separate page for each dropdown (e.g. apple.html, orange.html, etc) you could just hardcode the correct object on each page, but with AJAX you can make your code dryer by having a single page the form submits to, and depending on the value of the dropdown, make a call to a separate AJAX file (e.g. orange.js, apple.js) OR a sinle js file and grab the correct object:
xhttp.open("GET", "fruit.js", true)
then:
let orange = obj.orange
I hope that makes sense.

I was wondering if someone could teach me how to use cookies in my code

I'm trying to make a "Window.alert game" in a browser window for fun, but I can't figure out how to use cookies to save player data if they mess up or close the window. Can someone help me?
LocalStorage is indeed your best option for saving data semi-permanently. One thing to remember is that localStorage only supports strings, so if you need to store more complex objects, you should JSON.stringify them (and JSON.parse the result when loading data).
A simple pattern is to use a single object to store your state, and to save this state to localStorage whenever a change is made to it (so that your latest data is always persisted). You can also listen to the window.beforeUnload method to save your state right before the window closes, but this may not always work (eg: if your browser or tab closes unexpectedly).
Here is an example of what you can do:
// saves your state to localStorage
function save(state) {
localStorage.setItem('state', JSON.stringify(state));
}
// execute code when the document is loaded
document.addEventListener('DOMContentLoaded', function () {
// load your state from localStorage if it has been previously saved
// otherwise, set the state to an empty object
var state = JSON.parse(localStorage.getItem('state')) || {};
// show your name if previously saved
// otherwise, prompt for a name and save it
if (state.name) {
alert('Your name is: ' + state.name);
} else {
state.name = prompt('What is your name?');
save(state);
}
});
To clear localStorage, you can call localStorage.clear().

Property stored on 'window' object is removed on changing the 'Window.location.href'

I'm defining a property ( say, myVar ) on window object (to use it as a global variable ), but the problem is when I take the user on some different page by making use of window.location.href that global variable is lost, and becomes undefined.
Why is this unexpected behaviour of window obj variable is showing up, is it related to scope, and how to correct it ?
The window object is built on page load. After the page loads, you add the property and that stays with the object.
When you redirect the user to another page, this is (obviously) interpreted as a new page, which means a new page load. By then, the window object is completely new.
If you have to keep this variable between page refreshes, that a look at:
sessionStorage
Syntax
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key');
// Remove all saved data from sessionStorage
sessionStorage.clear();
localStorage
Syntax
// The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().
localStorage.setItem('myCat', 'Tom');
// The syntax for reading the localStorage item is as follows:
var cat = localStorage.getItem('myCat');
// The syntax for removing the localStorage item is as follows:
localStorage.removeItem('myCat');
//The syntax for removing all the localStorage items is as follows:
// Clear all items
localStorage.clear();
You could use the localStorage to store data that will persist between the pages of your website.
localStorage.setItem('myVar', value);
localStorage.getItem('myVar'); // gives value
https://developer.mozilla.org/fr/docs/Web/API/Window/localStorage

Save apikey between sessions

I'm making a little client-side web app for MagicCardMarket.eu. It's just javascript and html. The user has to log in using his username and apikey, though I was wondering what's the best way to save these between sessions?
It's the first time I make this kind of web app. It's also the first time I use anything like this apikey, so I wasn't sure what to Google.
Thanks!
You can use sessionStorage.
sessionStorage.setItem('key','value');
var value = sessionStorage.getItem('key');
So what is it?
This is a global object (sessionStorage) that maintains a storage area
that's available for the duration of the page session. A page session
lasts for as long as the browser is open and survives over page
reloads and restores. Opening a page in a new tab or window will cause
a new session to be initiated.
use session storage. It stores values as key, value pairs.
To set the value to session use
sessionStorage.name = "Use Name";
sessionStorage.APIKey = "Use APIKey";
To Get the values from session storage:
var name = sessionStorage.name;
var APIKey = sessionStorage.APIKey;
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

Javascript > form results to "remember" user > avoid showing form twice

I have a java script form in a website, that outputs some results -a silly simple mathematical operation or subtraction of dates.
I need these results to "remember" the visit so the div and the results
show when the user re-loads the page.
How can I achieve this?? It's my first time with facing a situation like this...
Note: its not a logged user!! but a non-logged visit..
http://goo.gl/OHQmpb
You can use localStorage.
Store the values in it by specifiying a key:
localStorage.setItem('key','value');
And, you can get the value by:
var value = localStorage.getItem('key');
HTML5 Web storage is the best option in your case.
Exact definition:
So what is HTML5 Storage? Simply put, it’s a way for web pages to
store named key/value pairs locally, within the client web browser.
Like cookies, this data persists even after you navigate away from the
web site, close your browser tab, exit your browser, or what have you.
Unlike cookies, this data is never transmitted to the remote web
server (unless you go out of your way to send it manually).
With HTML5, web pages can store data locally within the user's browser.
// Store it in object
localStorage.setItem("form attributes", "form values");
// Retrieve from object
localStorage.getItem("form attributes");
HTML5 Local Storage aka Web Storage can store values without maintaining a server side session. See this example:
function calculate(){
return 'some value';
}
window.onload = function(){
// submit handler for the form, store in local storage
document.getElementById("myform").onsubmit = function(){
localStorage.setItem('calcResult', calculate());
return false;
};
// load the value if present
var result = localStorage.getItem('calcResult');
if(result != null){
// show in div
document.getElementById("mydiv").innerHTML = result;
}
}

Categories

Resources