Retrieving value from HTML5 local storage - javascript

I have multiple JQM pages and in need to retrieve the active page ID i already stored and add it as a link to a button on the first page.
I am trying to achieve a "continue" function that allows you to not lose your progress.
In the example below I managed to store the active page ID and whenever the page is refreshed you will get an alert with the last page ID stored (first time it will alert #null cause no id is stored at the time).
It's basically ok but i can't seem to make that ID as the button link even though I tried $("#resume").attr("href", resume);
I am storing the ID with this button :
<a href="#" data-role="button" onclick='storageValue();'>Store</a>
And this is the function I have so far:
function storageValue() {
var stored = $.mobile.pageContainer.pagecontainer("getActivePage").attr('id');
alert("Your stored id is: " + stored);
localStorage.setItem('stored', stored);
checkLocalStorage();
}
var test = localStorage.getItem('stored');
var resume = "#" + test;
alert("Your stored id is: " + resume);
checkLocalStorage();
Optional: It would have been ideal if I didn't need to click a button to store the page. The page should be stored automatically when becoming active.
Here is a JSFIDDLE that will allow you to test/debug faster.
PS: I don't think it's of any relevance to this but I am going to turn this into an android app using XDK.

It's more practical to use pagecontainer events to store data. In your case, use pagecontainerhide to store ID of page you're navigating to toPage. And then, use pagecontainershow to update button's href.
In case stored ID is equal to first page's ID, the button will be hidden.
$(document).on("pagecontainerhide", function (e, data) {
var stored = data.toPage.attr('id');
localStorage.setItem('stored', stored);
}).on("pagecontainershow", function (e, data) {
if (data.toPage[0].id == "firstpage") {
var test = localStorage.getItem('stored');
var resume = "#" + test;
$("#resume").attr("href", resume);
if (test == "firstpage") {
$("#resume").fadeOut();
} else {
$("#resume").fadeIn();
}
}
});
Demo
If you want to navigate directly to last visited page, listen to pagecontainerbeforechange and alter toPage object.
$(document).on("pagecontainerbeforechange", function (e, data) {
if (typeof data.toPage == "object" && typeof data.prevPage == "undefined" && typeof localStorage.getItem('stored') != "undefined") {
data.toPage = "#" + localStorage.getItem('stored');
}
});
Demo

Related

Fill TextBox with data on page load using javascript

I'm working with a Google-Extention which allows me to open a new tab containing a form. After the form gets filled out and saved, every time I open this tab again the form should be prefilled with the data saved earlier.
Here is how the data gets saved: WORKS!
function saveCheckoutData() {
var vName = document.getElementById('txbx_name').value;
chrome.storage.sync.set({'name': vName}, function() {
console.log(vName);
})
}
Here is how i get the data: WORKS!
function getdata() {
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
The code above gets called on button click and works perfectly!
But as soon I try to do this when the tab gets opened it doesn't work (the tab gets opened but there is nothing in the textbox): DOESN'T WORK!
function configAutofill(){
var newURL = "autofill_data.html";
chrome.tabs.create({ url: newURL });
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
Does some one have an Idea why these lines do not work when creating a new tab?
Many thanks in advance.
Here's a question for you.
After creating a new tab, you access document.getElementById. Yes, but which document?
In your case, it would be the page calling create - which is not the created page.
In your case, it seems like you're opening a page that's part of the extension. Then you should just include code in it that will run on load.
You may want to check document.readyState:
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', getdata);
} else {
getdata();
}
If you're trying to do this with a webpage, you'll need a content script. Again, those normally execute after DOM is parsed - so just call getdata() at top level.

ajax image viewer , back button and history - missing html and css

I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});

send one of multiple search result to another page

I have a page userLanding.jsp
When a user performs a search the page will give multiple results.
I need to check selected dynamic result (succeeded so far),
Now the problem is I need to send/transfer/retrieve data of selected div to another page.
How can I do that?
Here is the code i am following to check which result is selected.
$('.demo-card-wide').click(function(){
article = $(this).text();
});
$(document).on('click', '.demo-card-wide', function(){
alert("clicked on result!!");
var id = this.id;
window.location = "http://localhost:8080/CarPool/test.jsp#"+id;
});
Since you are redirecting to a new page with the value you want set as the URL's hash, you can use window.location.hash to access that value on page load (though I wouldnt trust the data past that as it could be changed by the page after loading)
$(function(){
var id = window.location.hash;
// do something with id...
});
If you need to persist the data further than this, you might look into localstorage or a server side solution.
Just for grins, here is how I would do it (using localstorage):
Make this code available to both pages:
/**
* Feature detect + local reference for simple use of local storage
* Use this like:
* if (storage) {
* storage.setItem('key', 'value');
* storage.getItem('key');
* }
*
*/
var storage;
var fail;
var uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (exception) {}
/* end Feature detect + local reference */
On the first page have this:
$(document).on('click', '.demo-card-wide', function() {
if (storage) {
alert("clicked on result!!");
storage.setItem('article-id', this.id);
window.location = "http://localhost:8080/CarPool/test.jsp";
} else // some error message
});
On the second page, do this:
$(function() {
if (storage) {
var id = storage.getItem('article-id');
// do something with id...
}
});

how to show image on page refresh in localstorage

what i need
i need to show image when user select particular event. consider add to favorite functionality.
when user click on image data is store in array.
then user click particular image ,after reloading page another image should be shown at that position.
js code
on dom ready
show image on particular clicked div.
$(document).ready(function() {
console.log(localStorage);
if (localStorage.id!='')
{
var image_url='/images/star1_phonehover.png';
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
});
js code to set and get items
function favaorite(sess_id,name,city,country,event_url,pointer)
{
/* clear storage code*/
//window.localStorage.clear();
/* store imageurl in localstorage */
var imageUrl='/images/star1_phonehover.png';
// Save data to the current local store//
if (typeof(localStorage) == 'undefined' ) {
console.log('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else
{
try {
// Put the object into storage
localStorage.setItem('id' ,JSON.stringify(sess_id));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!');//data wasn't successfully saved due to quota exceed so throw an error
}
}
try {
// Put the object into storage
localStorage.setItem('name' ,JSON.stringify(name));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!');//data wasn't successfully saved due to quota exceed so throw an error
}
}
try {
// Put the object into storage
localStorage.setItem('city',JSON.stringify(city));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('country',JSON.stringify(country));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('event_url',JSON.stringify(event_url));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('imageUrl',JSON.stringify(imageUrl));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
/* fetch the data using from localstorage */
var id= [];
var name= [];
var city = [];
var country =[];
var event_url= [];
// Retrieve the object from storage
//var id, city, country,event_url;
var id = localStorage.getItem('id');
id = JSON.parse(id);
console.log(id);
var name = localStorage.getItem('name');
name = JSON.parse(name);
console.log(name);
var name = localStorage.getItem('name');
name = JSON.parse(name);
var city = localStorage.getItem('city');
city = JSON.parse(city);
console.log(city);
var country = localStorage.getItem('country');
country = JSON.parse(country);
console.log(country);
var event_url = localStorage.getItem('event_url');
event_url = JSON.parse(event_url);
///console.log(event_url);
var image_url = localStorage.getItem('imageUrl');
//event_url = JSON.parse(event_url);
alert(image_url);
//console.log(image_url);
//console.log($(pointer).closest('.evt_date').find('.star'));
if (id!='' )
{
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
}
Problem
i have stored image in localstorage and trying load image on page refresh so ist applying on all div which div i have not clciked marke as favorite.
here is snapshot of json data:
in snapshot you could see localstorage only stores single json.
i need to ask is localstorage don"t store whole data that i have clicked its hows recent data in localstorage.
output should be
select particular data and store in localstorage in nested json string.
and on dom load or page refresh show particular on div whose id stored in localstorage.
i have tried a solution
$(document).ready(function() {
console.log(localStorage.id);
if (localStorage.id==30301)
{
var image_url='/images/star1_phonehover.png';
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
});
then also it is applying image on all divs though it should apply on particular saved it of localstorage.
It sounds like you're trying to show a 'star' next to items a user has 'favorited' and you want to store these favorites in local storage.
Ignoring your existing code, I'd use a strategy like this:
1) Save the id's for each favorited item into an array and store that in local storage
localStorage.setItem('favorites' ,JSON.stringify(arrayOfFavorites));
2) On dom ready, add an attribute to all the 'favorited' items. Note, to do this you'll need to add some identifying attribute to each dom node you care about. I assume you have something like <div class='item' data-id='your-id'></div>:
var list = getArrayFromLocalStorage('favorites');
list.forEach(function(id) {
$('.item[data-id="' + id + '"').attr('favorite', '');
}
3) Finally, in your css, enable the background image for all items with the favorite attribute
item[favorite] {
background-image: '/images/star1_phonehover.png'
}
Hopefully this strategy points you in the right direction.

AJAX and setInterval for window.location.hash

//Gather AJAX links
var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink");
//Mark the recent state as null (because there is none yet)
var recentState = null;
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 500);
//Exit
return;
}
//Use AJAX for certain links
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
//Load the page state based on the URL
function loadStateFromURL() {
//If nothing has changed, exit
if (window.location.hash == recentState) {
return;
}
//Mark the recent state
recentState = window.location.hash;
//Go through an array of all AJAX links and check their IDs
for (var i = 0; i < ajaxLink.length; i++) {
//If we find a link's ID that matches the current state, load the relevant content
if ("#page=" + ajaxLink[i].id == window.location.hash) {
//Load contents into article.main
$("article.main").fadeOut(0).load(ajaxLink[i].href, function(response, status, xhr) {
//Show an error if the request fails
if (status == "error") {
$("article.main").load("./404.html");
window.location.hash = "page=404";
}
}).fadeIn(500);
//Update the page title
document.title = "\u2622 My Website Name \u2622 " + ajaxLink[i].text;
document.getElementById("headH2").textContent = ajaxLink[i].text;
//State has been fixed, exit
return;
}
}
}
This code works flawlessly when I run it locally!!!
But when I throw it on the web server my AJAX'd links will refresh the page when I first visit. However, if I use the back button then try the link again (or I'm assuming if the page is already in the browser cache), it will work properly.
I cannot allow this, because when people first visit my page the first link they click on will not operate as intended.
One of things I've also been testing is I'll bookmark my own site with a breadcrumb bookmark (example.com/#page=14) and see if it updates without my page already being in the browser cache. Again, it works on my local machine but not on my web server.
use event.preventDefault()
ajaxLink.click(function(e) {
e.preventDefault();
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
The issue maybe is that when you are applying your click event to these links, they may not be loaded to the DOM. So the possible solution is to put ajaxLink.click(function() { ... }); part inside window.load event or document.ready event. Since you have used window.load event, you can do something like this.
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 500);
//Use AJAX for certain links
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
//Exit
return;
}
Solved my own question, had to continuously parse the AJAX links to stay updated with the DOM as it changes.
First I put the ajaxLink declaration into a function:
//Gather AJAX links
function parseAjaxLinks() {
var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink");
return ajaxLink;
}
Then I had to put the ajaxLink click events into a function:
//Load the page state from an AJAX link click event
function loadStateFromClick() {
//Update the AJAX links
var ajaxLink = parseAjaxLinks();
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
}
Then I added a line in my window.onload event to keep my AJAX click events synchronized with the DOM (this adds overhead, but oh well):
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
recentState = window.location.hash;
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 250);
//Keep AJAX links synchronized (with DOM)
setInterval(loadStateFromClick, 250);
//Exit
return;
}
If you have a keen eye, you saw I had called the new parseAjaxLinks in my new loadStateFromClick function, so I added a line to the top of my loadStateFromURL function to keep the links updated in there as well:
//Load the page state based on the URL
function loadStateFromURL() {
//Update the AJAX links
var ajaxLink = parseAjaxLinks();
...
What I learned from this is the variables which are dependent on the DOM need to be continuously updated. While the DOM is loading, things are unpredictable and kind of sucks. **Drinks beer**

Categories

Resources