JavaScript local storage for pages - javascript

I have here a little script that I found and am using it to create a simple game of sorts...
/*
Here add:
'image_path': ['id_elm1', 'id_elm2']
"id_elm1" is the ID of the tag where the image is initially displayed
"id_elm2" is the ID of the second tag, where the image is moved, when click on the first tag
*/
var obimids = {
'http://www.notreble.com/buzz/wp-content/uploads/2011/12/les-claypool-200x200.jpg': ['lesto', 'les'],
'http://rs902.pbsrc.com/albums/ac223/walkingdeadheartbreaker/Muzak/Guitarists/LarryLalondePrimus.jpg~c200': ['lerto', 'ler'],
'http://www.noise11.com/wp/wp-content/uploads/2014/07/Primus-Alexander-200x200.jpg': ['timto', 'tim']
};
// function executed when click to move the image into the other tag
function whenAddImg() {
/* Here you can add a code to be executed when the images is added in the other tag */
return true;
}
/* From here no need to edit */
// create object that will contain functions to alternate image from a tag to another
var obaImg = new Object();
// http://coursesweb.net/javascript/
// put the image in element with ID from "ide"
obaImg.putImg = function(img, ide, stl) {
if(document.getElementById(ide)) {
document.getElementById(ide).innerHTML = '<img src="'+ img+ '" '+stl+' />';
}
}
// empty the element with ID from "elmid", add image in the other element associated to "img"
obaImg.alternateImg = function(elmid) {
var img = obaImg.storeim[elmid];
var addimg = (elmid == obimids[img][0]) ? obimids[img][1] : obimids[img][0];
$('#'+elmid+ ' img').hide(800, function(){
$('#'+elmid).html('');
obaImg.putImg(img, addimg, 'style="display:none;"');
$('#'+addimg+ ' img').fadeIn(500);
});
// function executed after the image is moved into "addimg"
whenAddImg();
}
obaImg.storeim = {}; // store /associate id_elm: image
// add 'image': 'id_elm1', and 'image': 'id_elm1' in "storeim"
// add the image in the first tag associated to image
// register 'onclick' to each element associated with images in "obimids"
obaImg.regOnclick = function() {
for(var im in obimids) {
obaImg.storeim[obimids[im][0]] = im;
obaImg.storeim[obimids[im][2]] = im;
obaImg.putImg(im, obimids[im][0], '');
document.getElementById(obimids[im][0]).onclick = function(){ obaImg.alternateImg(this.id); };
document.getElementById(obimids[im][3]).onclick = function(){ obaImg.alternateImg(this.id); };
}
}
obaImg.regOnclick(); // to execute regOnclick()
FIDDLE
When clicking the items it adds them to a container where I'd like them to be stored if the user navigates to another page. I have seen some local storage cookie code on another script
FIDDLE
var $chks = $('.compare').change(function () {
console.log('c', this)
if ($(this).is(':checked')) {
var img = $('<img>'),
findimg = $(this).closest('.box').find('img'),
data_term = findimg.data('term');
img.attr('src', findimg.attr('src'));
img.attr('data-term', data_term);
var input = '<input type="hidden" name="imagecompare" value="' + data_term + '">';
$('#area').find('div:empty:first').append(img).append(input);
} else {
var term = $(this).data('term'),
findboximage = $('#area > div > img[data-term=' + term + ']')
findboximage.parent('div').empty();
}
localStorage.setItem("imagecookie", $chks.filter(':checked').map(function () {
return $(this).data('term')
}).get().join(','));
});
$(document).on('click', '#area > div', function () {
$(this).empty();
localStorage.clear();
});
var cookie = localStorage.getItem("imagecookie");
if (cookie) {
var terms = cookie.split(',');
if (terms.length) {
$chks.filter($.map(terms, function (val) {
return '[data-term="' + val + '"]'
}).join()).prop('checked', true).change();
}
}
but can't figure how to apply something similar to this one. I would be grateful for any help or to be pointed to some useful places for help.

Related

Can't read undefined property for the second time

I've run into some problems while creating solitaire game.
I'm working on the remaining deck, on which, when clicked, will be show remaining cards, so player can cycle through them while clicking on the deck.
The problem itself: when you click on the deck code generates a picture file name taking parameters from 2 different arrays.
The first time after click the card appears without any error, but when one tries to click for the second time error appears: "Cannot read property 'Taskai' of undefined".
Code:
$.widget("Game.RemainingDeck", {
options: {
remainingDeck: []
},
_create: function() {
var game = this;
game.flipACard();
},
flipACard: function() {
var i = 0;
var game = this;
$("#remDeck").click(function() {
var remainDeck = game.options.remainingDeck;
var remDeck = $('#remDeck');
var oppenedCard = $('#openCard');
var card = $('<div class=" card"></div> ');
var imageName = remainDeck[i].Taskai + '_of_' + remainDeck[i].Simbolis + '.png';
var imagePath = 'texture/' + imageName;
card.css('background-image', 'url("' + imagePath + '")');
if (i = game.options.remainingDeck.lenght) {
aler("kaladë prasideda ið naujo");
}
i++;
oppenedCard.append(card);
});
}
})
i needs to be an outer var, otherwise it is 0 every time the click handler runs.
Also, I don't think the click handler should be attached in .flipcard(), otherwise it will be attached over and over, every time flipCard() is run. Try attaching the click handler in .create_().
$.widget("Game.RemainingDeck", {
options: {
remainingDeck: []
},
_create: function() {
var game = this;
var i = 0;
$("#remDeck").on('click', function() {
$('#openCard').append($('<div class=" card"></div>').css('background-image', 'url("texture/' + game.options.remainingDeck[i].Taskai + '_of_' + game.options.remainingDeck[i].Simbolis + '.png")'));
if(i === game.options.remainingDeck.length) {
alert("kaladë prasideda ið naujo");
}
i++;
});
this.flipACard();
},
flipACard: function() {
$("#remDeck").click();
}
})
Presumably you .pop() (or .shift()) cards off remainingDeck at some point? You could possibly do so on flipping, in which case the i counter is unnecessary.

localStorage clears on refresh, parse & stringify not working

Working on a practice app with localStorage, but the stored data is getting cleared on page refresh. Based on answers to similar questions, I've used JSON.stringify(); on setItem, and JSON.parse(); on getItem, but still no luck. Am I using those methods in the wrong way? For reference, #petType and #petName are input IDs, and #name and #type are ul IDs. Thanks!
var animalArray = [];
var addPet = function(type,name) {
var type = $("#petType").val();
var name = $("#petName").val();
localStorage.setItem("petType", JSON.stringify(type));
localStorage.setItem("petName", JSON.stringify(name));
animalArray.push(type,name);
};
var logPets = function() {
animalArray.forEach( function(element,index) {
//empty array
animalArray.length = 0;
//empty input
$("input").val("");
var storedName = JSON.parse(localStorage.getItem("petName"));
var storedType = JSON.parse(localStorage.getItem("petType"));
//append localStorage values onto ul's
$("#name").append("<li>" + storedName + "</li>");
$("#type").append("<li>" + storedType + "</li>");
});
};
//click listPets button, call logPets function
$("#listPets").on("click", function() {
logPets();
$("#check").html("");
});
//click enter button, call addPet function
$("#enter").on("click", function() {
addPet(petType,petName);
$("#check").append("<i class='fa fa-check' aria-hidden='true'></i>");
});
It appears to clear because you are not loading data from it when the page loads. There are multiple bugs in the code:
It appears that you're only saving the last added pet to localStorage, which would create inconsistent behaviour
Setting animalArray.length to 0 is incorrect
animalArray.push(type, name); is probably not what you want, since it adds 2 items to the array, do something like animalArray.push({type: type, name: name});
logPets can just use the in memory array, since it's identical to the one saved
Fixed code:
var storedArray = localStorage.getItem("animalArray");
var animalArray = [];
if(storedArray) {
animalArray = JSON.parse(storedArray);
}
var addPet = function(type,name) {
var type = $("#petType").val();
var name = $("#petName").val();
animalArray.push({type: type, name: name});
localStorage.setItem("animalArray", JSON.stringify(animalArray));
};
var logPets = function() {
animalArray.forEach( function(element,index) {
//empty input
$("input").val("");
//append localStorage values onto ul's
$("#name").append("<li>" + element.name + "</li>");
$("#type").append("<li>" + element.type + "</li>");
});
};
//click listPets button, call logPets function
$("#listPets").on("click", function() {
logPets();
$("#check").html("");
});
//click enter button, call addPet function
$("#enter").on("click", function() {
addPet(petType,petName);
$("#check").append("<i class='fa fa-check' aria-hidden='true'></i>");
});
A quick fiddle to demo it: https://jsfiddle.net/rhnnvvL0/1/

Page loading is gradually getting slower using jQuery script

I'm using this jQuery script to show search results. Everything works fine, but when search results have more than one page and I'm browsing pages via paging then every page loading is gradually getting slower. Usually first cca 10 pages loads I get quickly, but next are getting avoiding loading delay. Whole website get frozen for a little while (also loader image), but browser is not yet. What should be the problem?
function editResults(def) {
$('.searchResults').html('<p class=\'loader\'><img src=\'images/loader.gif\' /></p>');
var url = def;
var url = url + "&categories=";
// Parse Categories
$('input[name=chCat[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&sizes=";
// Parse Sizes
$('input[name=chSize[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&prices=";
// Parse Prices
$('input[name=chPrice[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
$('.searchResults').load('results.php'+url);
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
}
$(document).ready(function(){
editResults("?page=1");
// Check All Categories
$('input[name=chCat[0]]').click(function() {
check_status = $('input[name=chCat[0]]').attr("checked");
$('input[name=chCat[]]').each(function() {
this.checked = check_status;
});
});
// Check All Sizes
$('input[name=chSize[0]]').click(function() {
check_status = $('input[name=chSize[0]]').attr("checked");
$('input[name=chSize[]]').each(function() {
this.checked = check_status;
});
});
// Edit Results
$('.checkbox').change(function() {
editResults("?page=1");
});
// Change Type
$(".sort").change(function() {
editResults("?page=1&sort="+$(this).val());
});
});
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
just a wild guess but... wouldn't this piece of code add a new event handler to the click event instead reaplacing the old one with a new one? causing the click to call all the once registered handlers.
you should make the event binding just once
var global_var = '1';
function editResults(def) {
// all your code
global_var = 2; // what ever page goes next
};
$(document).ready(function() {
// all your code ...
$('.pageLinks').live("click", function() {
var page = global_var;
editResults("?page="+page);
});
});

How to hide a div after being appended to another div in jQuery?

I need to hide a div (this.elmWheel) after an ajax call is made .loadUrl().
Using this code I am not able to hide the div.
What am I doing wrong here?
I am using jquery 1.4.2
var Viewer = function(url) {
var scope = this;
this.elm = '#viewer';
this.elmWheel = '#loader-wheel';
this.url = url;
this.init = function() {
this.loadWheelInit();
this.loadUrl();
};
this.loadWheelInit = function() {
$('<div id="' + scope.elmWheel + '">Loading ...</div>').appendTo(this.elm);
};
this.loadWheelHide = function() {
$(this.elmWheel).hide();
console.log('hide');
};
this.loadUrl = function() {
// simulate loading
setTimeout(function() {
// fetch img from api
$.get(this.url, function(data) {
scope.loadWheelHide();
console.log('show image');
// add img to the dom
var img = $('<img id="img">');
img.attr('src', this.url);
img.appendTo(scope.elm);
});
}, 2000);
};
};
<div id="viewer" class="">
</div>
I am creating an instance with this code, image an Loadind wheel are appended correctly, just not able to hide it
var viewer = new Viewer('img/1.jpg');
viewer.init();
Then you are creating a loading wheel, it gets a wrong ID.
this.loadWheelInit = function() {
$('<div id="' + scope.elmWheel + '">Loading ...</div>').appendTo(this.elm);
};
This results in
<div id="#loader-wheel">Loading...</div>
In a loadWheelHide method, you are trying to access load wheel by selector #loader-wheel, but there are not such ID.
You need to store an ID in elmWheel
this.elmWheel = 'loader-wheel'
And prepend a hash sign when you do searching
this.loadWheelHide = function() {
$('#' + this.elmWheel).hide();
console.log('hide');
};

Why is some jQuery/javascript code being skipped?

I am currently coding an instant chatbox using jquery which will show the latest chat on top (refreshes when user send data via post request)
and push the oldest chat downward and remove it.
The problem is that if more than one latest chat is retrieved(for example, 2), two new div will be prepended but only one oldest div is removed instead of two...I tried timeout but it didnt work either..
Below are the code snippets I believe which got problem in it.
function showData(currentchatstyle, data, final){
var newchatstyle;
if (currentchatstyle == "chatone") {
newchatstyle = "chattwo";
}
else {
newchatstyle = "chatone";
}
$('div[class^="chat"]:first').before('<div class="' + newchatstyle + '" style="display:none;">' + data + ' </div>');
$('div[class^="chat"]:first').slideDown(500,"swing", function(){
$('div[class^="chat"]').last().fadeOut(500, function() {
$(this).remove();
});
});
return newchatstyle;
}
$('input[name="content"]').keyup(function(key) {
if (key.which==13) {
var author = $('input[name="author"]').val();
var content = $('input[name="content"]').val();
var lastnum = $('postn:first').text();
var chatstyle = $('div[class^="chat"]:first').attr("class");
$.post(
"chatajax.php",
{ "author": author, "content": content, "lastnum": lastnum },
function(data) {
var msg = data.split("|~|");
for (var i = 0; i < msg.length; i++) {
chatstyle = showData(chatstyle, msg[i], true);
}
}
);
}
});
Help will be very much appreciated.
The problem is that you do select also currently-fading-out divs with $('div[class^="chat"]').last(), as you don't remove them immediately but in the animation callback. You for example might immediately remove the chat class so it won't be selected in the next call to showData.
Also, you should only use one class "chat" for a similar divs and for a zebra-style give them independent classes.
var chatstyle = "one";
function showData(data, final){
chatstyle = chatstyle=="one" ? "two" : "one";
var newDiv = $('<div class="chat '+chatstyle+'" style="display:none;">'+data+'</div>');
$('div.chat:first').before(newDiv);
newDiv.slideDown(500, "swing", function(){
$('div.chat:last').removeClass('chat').fadeOut(500, function() {
// ^^^^^^^^^^^^^^^^^^^^
$(this).remove();
});
});
}
function post(data) {
return $.post(
"chatajax.php",
data,
function(data) {
var msg = data.split("|~|");
for (var i = 0; i < msg.length; i++)
showData(msg[i], true); // what's "final"?
}
);
}
$('input[name="content"]').keyup(function(key) {
if (key.which==13)
post({
"author": $('input[name="author"]').val(),
"content": $('input[name="content"]').val(),
"lastnum": $('postn:first').text() // I'm sure this should not be extracted from the DOM
});
});

Categories