Why is local storage not loading - javascript

Hello I am trying to do an Assessment where I need to be able to use the Local Storage in JavaScript.
I am very new to this but I cannot get my click counter to save. This is just a simple short game with text nodes but I am trying have a lifetime click counter, what am I doing wrong?
Also sorry if this is messy, this is my first application. This is also my first post so I hope this makes sense
JS
const lifetimeClicker = localStorage.getItem('counter')
var button = document.getElementById("counter"),
count = 0;
document.getElementById('option-buttons').onclick = function(Counter) {
count += 1;
button.innerHTML = + count;
};
function saveToLocalStorage () {
localStorage.setItem('lifetimeClicker', counter)
}
document.getElementById('saveButton').onclick = saveToLocalStorage
HTML
<body>
<div class="textButtons">
<div id="textSize">Text Size</div>
<button class="btn" onclick="document.getElementById('text').style.fontSize = '1.0em'">S</button>
<button class="btn" onclick="document.getElementById('text').style.fontSize = '1.5em'">M</button>
<button class="btn" onclick="document.getElementById('text').style.fontSize = '2.0em'">L</button>
<div class="main">
<div class="main">
<h3>Lifetime Clicks</h3>
<p id="counter">0</p>
<button id="saveButton">Save</button>
</div>
</div>
<div class="container">
<div id="text">Text</div>
<div id="option-buttons" class="btn-grid">
<button class="btn" onclick="'clicks = clicks++'">Option 1</button>
<button class="btn" onclick="'clicks = clicks++'">Option 2</button>
<button class="btn" onclick="'clicks = clicks++'">Option 3</button>
<button class="btn" onclick="'clicks = clicks++'">Option 4</button>
<button class="btn" onclick="'clicks = clicks++'">Option 5</button>
</div>
</div>
</body>
The Option Buttons carryout out the next text and options for the next scene.
At the moment each time I click an option-button it goes to the next textnodes and the counter increments +1This is what it all looks like together

You are getting an item with the reference of counter in Local Storage, but when you are setting it, you set to lifetimeClicker. Change the first line of your code to:
const lifetimeClicker = localStorage.getItem('lifetimeClicker')
Or, inside saveToLocalStorage, use counter as the first argument of localStorage.setItem

Try the below:
//We are using the key "current-count" to identify the value we need (you can name this anything)
//Values in storage must always be strings
const countData = localStorage.getItem("current-count")
const savedData = JSON.parse(countData);
localStorage.setItem("current-count", JSON.stringify(counter));

Related

Want to add button at the bottom but with lowest index value

<button class="btn" onclick="func(0)" value="">abc</button>
<button class="btn" onclick="func(1)" value="">def</button>
<button class="btn" onclick="func(2)" value="">ghi</button>
<script type="text/javascript">
function func(i){
var btn= document.getElementsByClassName("btn")[i];
console.log(btn);
btn.style.color="red";
}
</script>
I want to add new button every time, and want to display them on top. For adding them on top i need to change numbering till end
any solution to this. How new button[i] can be displayed on top
Subtract from the number of buttons to count from the end.
function func(i) {
var all_buttons = document.getElementsByClassName("btn");
all_buttons[all_buttons.length - i - 1].style.color = "red";
}
<button class="btn" onclick="func(2)" value="">abc</button>
<button class="btn" onclick="func(1)" value="">def</button>
<button class="btn" onclick="func(0)" value="">ghi</button>

querySelectorAll not working with Cloned item

I'm trying to make a copy of the original container div with the cloneNode method in javascript inside the container there are 3 buttons with btn class, when I make a copy of the original one the last only the last element in the copied item is only printing hello in the console, any ideas?
let add = document.querySelector('.add-button');
const item = document.querySelector('.container');
let btn = document.querySelectorAll('.btn');
add.addEventListener('click', function() {
makecopy();
});
btn.forEach(el => {
el.addEventListener('click', function() {
console.log("hello")
})
});
function makecopy() {
let copiedItem = item.cloneNode(true);
item.parentNode.insertBefore(copiedItem, item);
}
<div class="add-panel">
<button type="button" class="add-button">Create new</button>
</div>
<div class="container">
<div>
<button type="button" class="btn">+</button>
</div>
<div>
<button type="button" class="btn">+</button>
</div>
<div>
<button type="button" class="btn">+</button>
</div>
You are only setting up event listeners on the first set of buttons, not the cloned ones. Instead of setting up listeners on each button, use "event delegation" to allow the event to "bubble" up to a common ancestor and handle the event there. This way, all the newly added elements will immediately work without needing their own handler and there is only one handler that needs to be set up instead of many.
You've also got some redundant code and code that will no longer be needed when you take this approach.
// No need to set up an anonymous handler that calls the real one. Just
// register the real one
document.querySelector('.add-button').addEventListener('click', makecopy);
const item = document.querySelector('.container');
function makecopy() {
let copiedItem = item.cloneNode(true);
item.parentNode.insertBefore(copiedItem, item);
}
// Listen for clicks on the document:
document.addEventListener('click', function(event) {
// Check to see if it was a button that was clicked:
if(event.target.classList.contains("btn")){
console.log("hello");
};
});
<div class="add-panel">
<button type="button" class="add-button">Create new</button>
</div>
<div class="container">
<div>
<button type="button" class="btn">+</button>
</div>
<div>
<button type="button" class="btn">+</button>
</div>
<div>
<button type="button" class="btn">+</button>
</div>
</div>
Just appears you weren't adding new listeners when you made new buttons. Some adjustments.
let add = document.querySelector('.add-button');
const item = document.querySelector('.container');
let btn = document.querySelectorAll('.btn');
add.addEventListener('click', function() {
makecopy();
});
btn.forEach(el => {
el.addEventListener('click', function() {
console.log("hello")
})
});
function makecopy() {
let copiedItem = item.cloneNode(true);
item.parentNode.insertBefore(copiedItem, item);
copiedItem.addEventListener('click', function() {
console.log("hello")
})
}
<div class="add-panel">
<button type="button" class="add-button">Create new</button>
</div>
<div class="container">
<div>
<button type="button" class="btn">+</button>
</div>
<div>
<button type="button" class="btn">+</button>
</div>
<div>
<button type="button" class="btn">+</button>
</div>

Different values for innerHTML in debug and console log

I'm encountering a typical situation while accessing the innerHTML property using jQuery. I've fetched the target button using the jQuery attribute selector.
Below is the snippet of jQuery attribute selector.
jQuery('button[type="button"][class="btn btn-primary"]').each(function () {
var btn = jQuery(this);
console.log(btn);
if (btn[0].innerHTML === "OK") {
console.log("ok");
jQuery(this).click();
}
});
Following is the screenshot of the console log of the target button. It's innerHTML property is set to OK.
Following is the screenshot of the value of the innerHTML while debugging the target button object. In this case the value is "".
Ideally, the values of the innerHTML should be the same for both the cases.
EDIT
Why does this behavior differ that the ideal one? For both of the cases, the value of the innerHTML should be the same.
Also, there were multiple buttons. I have taken screenshots of different buttons. Thus their ID's are different. But still, the behavior is same.
Try something like this.
function SomeEvent($ele) {
alert($ele.html());
return false;
}
function invokeBtnEvents() {
$("[data-action=some-event]").off(); // clear old events
$("[data-action=some-event]").on("click", function() {
var $this = $(this);
return SomeEvent($this);
}) // define event(s)
return false;
}
$(document).ready(function() {
invokeBtnEvents();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event" class="btn btn-primary">Button 1</button>
<button data-action="some-event" class="btn btn-primary">Button 2</button>
<button data-action="some-event" class="btn btn-primary">Button 3</button>
<button data-action="some-event" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>
Your issue
What you are doing that I think is your main issue is the $.each() method.
Store the buttons in a variable,
let $button = $("button"); // this returns an array of all the buttons on the DOM
You can then use the $.each() method to get the clicked element
$.each($button, function(index, btn){
const $this = $(btn);
$this.off();
$this.click(function(){someEvent($this)});
});
I would not invoke button clicks like this because every time you click a button, this each loop gets ran. It will then send all of the buttons to that action unless you parse by an ID or something (you are using the innerText).
If you use the code in my snippet, only the clicked button will be triggered.
An alternative approach to my first snippet is using something like a dispatcher.
function DoActionOneClick($ele){
alert("Action 1 " + $ele.html());
}
function DoDefaultClick($ele){
alert("Default Action " + $ele.html());
}
function DispatchEvent(action, $ele){
switch(action){
case "some-event-1":
DoActionOneClick($ele);
break;
default:
DoDefaultClick($ele);
break;
}
}
function invokeActions(){
$("[data-action]").off();
$("[data-action]").on("click", function(){
// get this
var $this = $(this);
// get action
var action = $this.data().action;
DispatchEvent(action, $this);
});
}
$(document).ready(function(){
invokeActions();
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event-1" class="btn btn-primary">Button 1</button>
<button data-action="some-event-2" class="btn btn-primary">Button 2</button>
<button data-action="some-event-2" class="btn btn-primary">Button 3</button>
<button data-action="some-event-2" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>

How can I get a substring of an ID name?

I have a number of buttons within a section, each with an id of the form #balls-left-n, where n ranges from 1 to 15.
When one of these buttons is clicked, I want to grab the number from the id that was clicked and hide all of the buttons with ids that have names including numbers that are greater than the one clicked on.
So, if #balls-left-13 is clicked, I want to hide #balls-left-14 and #balls-left-15. But if #balls-left-3 is clicked I want to hide all the buttons from #balls-left-4 through #balls-left-15.
I'm a novice at web-dev so if I've made other mistakes or taken a poor approach don't hesitate to point that out.
I have a handler for each of the buttons (which if I knew more could probably be one function) that look like this:
$("#balls-left-14").click(function() {
var num_balls = $(this).attr('id').match(/[\d]/);
j_end_balls_on_table = 14;
$("#balls-left button:gt(num_balls-2)").hide;
...
other stuff
...
});
This didn't work and I get an error that num_balls is undefined, which I don't understand.
#balls-left is the section all of the buttons are inside of.
relevant HTML as requested
<section id="balls-left">
<h2>How Many Balls are Left on the Table?</h2>
<button type="button" id="balls-left-2" class="x-balls-left">2</button>
<button type="button" id="balls-left-3" class="x-balls-left">3</button>
<button type="button" id="balls-left-4" class="x-balls-left">4</button>
<button type="button" id="balls-left-5" class="x-balls-left">5</button>
<button type="button" id="balls-left-6" class="x-balls-left">6</button>
<button type="button" id="balls-left-7" class="x-balls-left">7</button>
<button type="button" id="balls-left-8" class="x-balls-left">8</button>
<button type="button" id="balls-left-9" class="x-balls-left">9</button>
<button type="button" id="balls-left-10" class="x-balls-left">10</button>
<button type="button" id="balls-left-11" class="x-balls-left">11</button>
<button type="button" id="balls-left-12" class="x-balls-left">12</button>
<button type="button" id="balls-left-13" class="x-balls-left">13</button>
<button type="button" id="balls-left-14" class="x-balls-left">14</button>
<button type="button" id="balls-left-15" class="x-balls-left">15</button>
</section>
Hope this helps.
var exploded = id.split("-");
alert(exploded.pop());
Now, to use that concept on your HTML structure, you can do something like this:
$(document).ready(function() {
$(".x-balls-left").click(function(e) {
e.preventDefault();
var exploded = this.id.split("-");
alert(exploded.pop());
});
});
And here's a Fiddle you can play around with.
You might don't even need all of these if your elements to hide share the same parent. Just set class on click .selected and hide the rest using CSS .selected.x-balls-left ~ .x-balls-left {display: none;}
$('.x-balls-left').click(function() {
$(this).toggleClass('selected');
})
.selected.x-balls-left ~ .x-balls-left {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="balls-left">
<h2>How Many Balls are Left on the Table?</h2>
<button type="button" id="balls-left-2" class="x-balls-left">2</button>
<button type="button" id="balls-left-3" class="x-balls-left">3</button>
<button type="button" id="balls-left-4" class="x-balls-left">4</button>
<button type="button" id="balls-left-5" class="x-balls-left">5</button>
<button type="button" id="balls-left-6" class="x-balls-left">6</button>
<button type="button" id="balls-left-7" class="x-balls-left">7</button>
<button type="button" id="balls-left-8" class="x-balls-left">8</button>
<button type="button" id="balls-left-9" class="x-balls-left">9</button>
<button type="button" id="balls-left-10" class="x-balls-left">10</button>
<button type="button" id="balls-left-11" class="x-balls-left">11</button>
<button type="button" id="balls-left-12" class="x-balls-left">12</button>
<button type="button" id="balls-left-13" class="x-balls-left">13</button>
<button type="button" id="balls-left-14" class="x-balls-left">14</button>
<button type="button" id="balls-left-15" class="x-balls-left">15</button>
</section>
$(document).on('click', '.balls-left', function() {
var num = getNum(this);
$('.balls-left').each(function() {
var that = $(this);
var bnum = getNum(that);
if (bnum > num) {
that.show();
} else {
that.hide();
}
});
});
var getNum = function(elem) {
if (elem) {
return $(elem).attr('id').replace('balls-left-', '');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="balls-left-1" class="balls-left">Ball 1</div>
<div id="balls-left-2" class="balls-left">Ball 2</div>
<div id="balls-left-3" class="balls-left">Ball 3</div>
<div id="balls-left-4" class="balls-left">Ball 4</div>
<div id="balls-left-5" class="balls-left">Ball 5</div>
$("#balls-left button:gt(num_balls-2)").hide;
This is an invalid CSS selector, and only gets the hide method, without calling it. You want something like:
$("#balls-left button:gt("+(num_balls-2)+")").hide();
First you should put a class on each object so you can reference them all at once, and the simplest way to understand is to just put the ball number right in the tag as a custom attribute if you can:
<input type="button" id="balls-left-1" class="left-ball" num="1"/>
<input type="button" id="balls-left-2" class="left-ball" num="2"/>
etc...
Then you can write the javascript as follows:
$('.left-ball').click(function () {
var BallNum = $(this).attr('num');
$('.left-ball').each(function () {
if ($(this).attr('num') > BallNum) {
$(this).hide();
}
});
});
You can use RegEx match like this. This might resolve your undefined num_balls error message.
$("#balls-left-14").click(function() {
var ret = $(this).attr('id').match("[0-9]+");
var num_balls = ret[0];
j_end_balls_on_table = 14;
$("#balls-left button:gt(num_balls-2)").hide;
...
other stuff
...
});
Another way of doing it using your original HTML:
$('.x-balls-left').click(function () {
var BallNum = $(this)[0].innerHTML;
$('.x-balls-left').each(function () {
if ($(this)[0].innerHTML > BallNum) {
$(this).hide();
}
});
});
I just did it like this:
$('button[id^=balls-left-]').click(function(){
var num_balls = $(this).attr('id').match(/[\d]/);
$('#balls-left button:gt(' + num_balls + ')').hide();
});
Keep in mind that :gt select by index, it means that $('#balls-left button:gt(2)') will not select the button with id balls-left-2 but the one with id balls-left-4 (according to the html you posted).

Trying to make a button in JavaScript but it's not working

I'm new in JavaScript and I took an app here to learn how to use the language.
So, In my index.html I have this code here:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
and this as footer:
`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`
What I'm basically trying to do is just reset the score to zero. But It's not working...
I tried to put some alert() inside reset() function but didn't work also.
Does someone has a clue why this is happening?
Thanks for helping!
Use onclick property:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore" onclick="reset()">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
You are declaring the function but not calling it anywhere. So you need to call the function at onclick event of button.
You should add an event listener for the click event.
Because of your comment, you can change the DOM by changing the inner HTML, see below snippet and code:
document.getElementById('resetscore').addEventListener('click',function() {
//localStorage.setItem('total_win', 0);
//localStorage.setItem('total_lose', 0);
document.getElementById('total_win').innerHTML = 0;
document.getElementById('total_lose').innerHTML = 0;
});
document.getElementById('win').addEventListener('click',function(){
var a = parseFloat(document.getElementById('total_win').innerHTML);
document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
document.getElementById('loss').addEventListener('click',function(){
var b = parseFloat(document.getElementById('total_lose').innerHTML);
document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);
});
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<button type="button" id="win">+1 Win</button>
<button type="button" id="loss">+1 Loss</button>
</div>
<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>
your script tag can't be inside a div. You need to move all your javascript to the end of your body, right before its closing tag, after all the html
Just add this:
<button type="button" onclick="reset()" id="resetscore">
You need to tell which one of your functions to use, notice the onclick, it does just that, so reset executes on click
Your button needs to call reset
<button type="button" id="resetscore" onclick="reset()">Reset</button>

Categories