how to show image on page refresh in localstorage - javascript

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.

Related

testing 2-player socket.io game. updating a label is affecting both pages

I don't understand why updating a label on one page is affecting the label on another page. I did not think the DOM was shared like that. Opening one tab or page successfully updates the label to 'player1', but when I open another tab/pg, it updates both labels to 'player2'.
<script>
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.emit('join');
socket.on('joinSuccess', function (playerSlot) {
if (playerSlot === 'player1') {
$("#playerID").text("you are player1");
} else if (playerSlot === 'player2') {
$("#playerID").text("you are player2");
}
}); //end joinSuccess
}); //end connect
I am merely trying to notify the user which player they are.
solution:
else if (playerSlot === 'player2') {
var elm = $("#playerID");
var empty = !elm.text().trim();
if (empty) {
elm.text("you are " + playerSlot);
}
}
Are you pushing the 'joinSuccess' message when new user joins? In such case this message will be passed to both the pages with same playerSlot value. So, all pages will be updated last joined player name.
In such case you can handle this with simple condition,
socket.on('joinSuccess', function (playerSlot) {
var elm = $("#playerID");
if (!elm.text().trim()) {
elm.text("you are " + playerSlot);
}
});

How to stop the same data from being added to local storage

Hi im farily new to javascript and i would like to know a simple method of
how i can make sure that i can only favourate an item once else it doesnt get added to the local storage and displays a message stating it already exists.
so far i have done the following :
$(".add").on( "click", function() {
try {
$(this).attr('disabled', true);
var IdToAdd = $(this).closest("p").attr("id");
var myFavStaff = JSON.parse(localStorage.getItem("favStaff"));
if (myFavStaff == null) {
myFavStaff = [];
}
myFavStaff .push(IdToAdd );
localStorage.setItem("favStaff", JSON.stringify(myFavStaff ));
}
catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log("Error: Local Storage limit exceeded" );
} else {
console.log("Error: Saving to local storage not working" );
}
}
});
With the technique you are using you will need to check the array before adding a new ID to it. For example you could do something like this.
if (myFavStuff.indexOf(IdToAdd) !== -1) {
// Already exists so show a message
} else {
myFavStuff.push(IdToAdd);
localStorage.setItem("favStaff", JSON.stringify(myFavStaff ));
}

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...
}
});

Retrieving value from HTML5 local storage

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

Receive Events in a javascript and print it in a separate window?

I have a pushlet in my project which receives the push events (i.e.,) if a user click on some buttons it will get the action and sends the message to the main jsp page through a javascript. Now, i have received datas through the pushlet and retrieved those in a javascript.
function setUserDataEvent(UserDataEvent) {
try {
alert(UserDataEvent);
}
catch(er) {
}
}
Where userDataEvent is the event which i received through pushlet. I am getting continuous alerts like for eg.,(a=b) and then (c=d). I have to receive get those values and then print those in a separate window in javascript using window.open()....
Any suggestions???????
I think you have to go over a cookie.
Save the event data in a cookie, then open the window and then, in your script in the window, read the data and delete the cookie.
I arrived at a solution and its working fine!!!!!
var testWindow;
var testData="";
function setUserDataEvent(UserDataEvent) {
try {
if(!testData) {
testData = UserDataEvent;
} else {
testData += UserDataEvent;
}
if(!testWindow) {
var x = 235;
var y = 370;
testWindow = window.open('','q',"location=no,directories=no,status=no,menubar=no,scrollbars=no,resize=no,width=" + x + ",height=" + y);
}
testWindow.document.write(testData);
testWindow.document.close();
testWindow.focus();
}
catch (er)
{
}
}

Categories

Resources