HTML5 Local Storage - multiple removeItem issue - javascript

I'm fiddling about with HTML5 local storage (not had much of a chance to play with it before) and I thought I'd make a little note-taker sort of thing.
I have a function which reads what's in the local storage and displays it on the page, which works fine until you try and delete more than one entry.
function renderNotes() {
$(currentNotes).html('');
Object.keys(localStorage);
Object.keys(localStorage).length;
$.each(localStorage, function(key, value){
$(currentNotes).append('<div class="note"><div class="noteHeader"><p class="noteName">' + key + '</p></div><div class="noteContent"><p>' + value + '</p></div></div>');
});
alert('notes rendered');
}
Go to the JSFiddle: http://jsfiddle.net/AThomas92/MSxQ9/3/ and try deleting some entries by clicking on the bold headers below the form - the first time it works fine, but after that it doesn't work at all.
The weird thing is, the function is also called when you add a new note, and it works over and over again.
Any ideas?
Thanks in advance,
Ash

Since the elements are re-rendered dynamically, you need to use event delegation
// DELETE NOTE
$(document).on('click', '.noteName', function(){
var noteName = $(this).html();
localStorage.removeItem(noteName);
renderNotes();
});
Demo: Fiddle

In addition to Arun P Johny's answer, here is an hint for your use of jquery :
Instead of using jquery object like the following :
var saveBtn = $('#saveBtn');
$(saveBtn).click(function(){
// Code
});
Use it like that :
var saveBtn = $('#saveBtn');
saveBtn.click(function(){
// Code
});
Or even better (to remember that it is a jquery object) :
var $saveBtn = $('#saveBtn');
$saveBtn.click(function(){
// Code
});

Related

How can I create a dynamic product page using HTML, CSS, and Javascript

I currently only know javascript. But the thing is I looked up how to do it and some people talk about something called localStorage. I have tried this and for some reason when I jump to a new page those variables aren't kept. Maybe I am doing something wrong? I jump to a new page via
and all I want do do is select a certain image. take that image to a new page and add it to that page.
I tried using the localStorage variables and even turning it into JSON.stringify and doing JSON.parse when trying to call the localstorage to another script. It didn't seem to work for me. Is there another solution?
This is some of my code. There are two scripts.
document.querySelectorAll(".card").forEach(item => {
item.addEventListener("click", onProductClick);
})
var div;
var productImg;
var ratingElement;
var reviewCount;
var price;
function onProductClick(){
// This took a week to find out (this.id)
// console.log(this.id);
div = document.getElementById(this.id);
productImg = div.getElementsByTagName('img')[0];
ratingElement = div.getElementsByTagName('a')[2];
reviewCount = div.getElementsByTagName('a')[3]
price = div.getElementsByTagName('a')[4];
console.log(div.getElementsByTagName('a')[4]);
var productData = [div, productImg,ratingElement,reviewCount,price];
window.localStorage.setItem("price", JSON.stringify(price));
}
function TranslateProduct(){
console.log("Hello");
}
This is script 2
var productPageImage = document.getElementById("product-image");
var myData = localStorage['productdata-local'];
var value =JSON.parse(window.localStorage.getItem('price'));
console.log(value);
// function setProductPage(img){
// if(productImg != null){
// return;
// }
// console.log(window.price);
// }
To explain my thought process on this code in the first script I have multiple images that have event listeners for a click. I wanted to Click any given image and grab all the data about it and the product. Then I wanted to move that to another script (script 2) and add it to a dynamic second page. yet I print my variables and they work on the first script and somehow don't on the second. This is my code. in the meantime I will look into cookies Thank you!
Have you tried Cookies
You can always use cookies, but you may run into their limitations. These days, cookies are not the best choice, even though they have the ability to preserve data even longer than the current window session.
or you can make a GET request to the other page by attaching your serialized object to the URL as follows:
http://www.app.com/second.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using JavaScript.
you can check this answer for more details Pass javascript object from one page to other

How to store a newly created element to localStorage or Cookie with Javascript?

I am making an idle clicker game for fun, everything was going fine until I encountered a problem.
What I basically want to happen is when the image is clicked and the clickCounter element is over one, the new image element is created. No problem here, the main problem is saving the image. If the user refreshes the page, I want the created element to still be there. I have tried using outerHTML and following some other Stack Overflow forum questions but I could never get a proper solution to this certain problem. I have also tried localStorage and cookies but I believe I am using them wrong.
My code is below, my sololearn will be linked below, consisting of the full code to my project.
function oneHundThou() {
var countvar = document.getElementById("clickCounter")
if(document.getElementById("clickCounter").innerHTML > 1) {
alert("Achievement! 1 pat!")
var achievement1k = document.createElement("img");
// create a cookie so when the user refreshes the page, the achievement is shown again
document.cookie = "achievement1k=true";
achievement1k.src = "https://c.pxhere.com/images/f2/ec/a3fcfba7993c96fe881024fe21e7-1460589.jpg!d";
achievement1k.style.height = "1000px"
achievement1k.style.width = "1000px"
achievement1k.style.backgroundColor = "red"
document.body.appendChild(achievement1k);
oneHundThou = function(){}; // emptying my function after it is run once instead of using a standard switch statement
}
else {
return
}
}
oneHundThou();
I am aware that there is another post that is similar to this, however, my answer could not be answered on that post.
Full code is here: https://code.sololearn.com/Wwdw59oenFqB
Please help! Thank you. (:
Instead of storing the image, try storing the innerHTML, then create the image on document load:
function oneHundThou() {
countvar.innerHTML = localStorage.getItem('clickCount') ? localStorage.getItem('clickCount') : 0; //before if
//original code
localStorage.setItem('clickCount', countvar.innerHTML); //instead of doc.cookie
}
window.addEventListener('DOMContentLoaded', (event) => {
oneHundThou();
});
or, if you don't care that clickCounter may initialize to null, you can remove the ? : and just put
countvar.innerHTML = localStorage.getItem('clickCount');
Edit: shortened code with the countvar variable

How can I prevent jQuery from triggering multiple times even with unbinders?

I have both a PHP (demo.php) and JavaScript file (demo.js). I have a function that is supposed to create and object over a server, return it's key, use it to create its path, and then create a URL to it. However, only one URL can be active at a time so it is important that this only happens once. However, it is happening multiple times, and often sending me to a retired link. The last link created always works, but I want to prevent having to go looking for the links generated by this error.
My PHP (demo.php) looks very much like:
<div id="svg_graph">
// just a graph (code is irrelevant)
</div>
<div id="prompt">
<a id="startup" class="button"> Create New Object </a>
</div>
And my JS looks like:
function funcA(){
$("#svg_graph").mousedown(function(){
$(this).mousemove(function(e){
// irrelevant code
});
});
$("#svg_graph").mouseup(function(){
// $("a#startup").bind("click",function(){ // doesn't work either
$("a#startup").click(function(){
// Supposed to prevent multiple clicks, but doesn't
$("a#startup").unbind("click");
funcB();
});
$(this).unbind("mousemove");
});
}
// This function is being called more than once but I don't know why
function funcB(data){
var obj = createObj(data);
var url = "some predefined url" + obj.key;
window.location.replace(url);
)
These days, you should be using .off(), though .unbind() should stil work.
If unbinding is indeed the issue, then you might have better luck with :
$("#svg_graph").off('mouseup').on('mouseup', function() {
$("a#startup").off('click').on('click', function() {
funcB();
return false; // probably
});
});

Adding OnClick Event with Javascript is not working

I'm trying to add an onclick event with JavaScript.
$.getJSON(api , function(data) {
//First Option found (not working)
//document.getElementById("today_button").SetAttrribute("onclick", "window.location.replace('" + data[1] + "')");
//Second Option found (not working either)
document.getElementById('today_button').onclick = "window.location.replace('" + data[1] + "');";
});
The Variables exist, the Event is fired, the data transmitted are correct and everything except this works just fine (like altering the disabled state of exactly this button).
I hope you can help me
You need to assign a function to onclick, not a string:
document.getElementById('today_button').onclick = function(event) {
window.location.replace(data[1]);
}
Why are you assigning a string as a click handler? Just use a function.
document.getElementById('today_button').onclick = function () {
location.replace(data[1]);
};
The problem is you assigned string to onclick, but it needs function.
document.getElementById('today_button').onclick = function() {
window.location.replace(data[1]);
}

Calling url assigned in a var

While playing around with Raphael.js Australia map, I tried assigning URLs for each element by changing their attribute in the end of the path:
country.cityone = R.path("coordinates").attr({href: "cityone.html"}).attr(attr);
country.citytwo = R.path("coordinates").attr({href: "citytwo.html"}).attr(attr);
...
The above works with Firefox, Chrome etc, but IE6-IE9 have trouble with that declaration.
So I thought of declaring another variable after var country and assigning the urls to that:
var url = {};
url.cityone = "cityone.html";
url.citytwo = "citytwo.html";
then calling it on mouse click/down:
st[0].onmousedown = function() {
current && country[current] && document.getElementById(“current”).appendChild(url);
};
However it won't work at all. Apparently I'm not making the call properly from the function, to relate each URL to its respective city. What am I missing?
I haven't tested this but I'm pretty sure you should just do away with the href and add a mouse event:
country.cityone = R.path("coordinates").attr(attr).click(function(){
window.location.href = "cityone.html";
});
I'm pretty sure that will work.
Just to close this question, after several trials, I ended up finding out that IE requires a double-click on click(function(){ for the href page to open up
I found out that in the above code:
country.cityone = R.path("coordinates").attr(attr).click(function(){
window.location.href = "cityone.html";
});
I had to change the .click(function(){ into .mousedown(function(){ for IE to work as it should.
Thank you #Zevan!
Cheers

Categories

Resources