HTML5 Localstorage help needed - javascript

I'm fresh to JS and i was wondering how i could implement this scenario to my code.
Im creating a simple tapping game for android using html, css and js. Whenever my object gets clicked on, 10 points gets added to score. I need this score to saved locally. So when the game restarts the score is there loaded.
Here are the game code:
var score = 0;
$(document).ready(function() {
$("#menu").hide();
$("#bug").autoBounceOff(true);
$("#bug").moveTo(140);
$("#bug").speed(0.8);
//When bug is clicked on
$("#bug").click(function() {
score = score + 10;
$('#score').html('Points: ' + score + '') + 10;
});
})
function showMenu() {
$("#menu").show();
$("#bug").css("visibility", "hidden");
$("#bug").css("animation-play-state", "paused");
return;
}
function resume() {
$("#menu").hide();
$("#bug").css("visibility", "visible");
$("#bug").css("animation-play-state", "running");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<div id="score">Points:</div>
<div id="menuheader" onclick="showMenu()">M</div>
</div>
<div id="menu">
<div id="start" onclick="resume()">resume</div>
</div>
<div id="bug"></div>
<div class="bottomwall"></div>
<div class="topwall"></div>
<div class="leftwall"></div>
<div class="rightwall"></div>
JSFiddle

basic localStorage usage.
When you starting your script, you can test if localStorage.score is already set with:
var score = 0;
if(!localStorage.score){
localStorage.score = 0;
}
score = parseInt(localStorage.score);
then in your click event:
localStorage.score = score + 10

please check this link can help you :
http://www.w3schools.com/html/html5_webstorage.asp
you can make an empty array and use: array_name.push() for your values.
then you can use localStorage.setItem("score" , array_name) and you can retrieve this value again using: localStorage.getItem("score"); that return array values and you should check first: if it has values or not to avoid undefined or exceptions in your application.
if you need a demo for this just tell me now and i will upload it.

Related

Random images flickering during slideshow using reddit json api

Goal:
Photo slider where you can toggle between different subreddits and view recent photos which have been posted.
Issue:
When you select one subreddit (via dedicated button) and scroll through a few photos (forward and/or back) all works fine, however if you then choose a different subreddit (via dedicated button) and scroll through a few photos (forward and/or back) the photos from the prior/first subreddit you previously selected flicker in and out at seemingly random intervals. I have watched console while this happens and src url for whatever photo that flickers in/out never enters the img element (unless its happening too fast to catch), instead the src url goes directly to the expected image. Also, I am console logging the array of image urls as the sub is selected via click and there is no abnormalities (all the photo links in the array are from the correct subreddit and in the correct order).
What I have tried:Moving the empty array var into the loop itself and the if statement, moving the counter variable into the functions themselves, as well as wrapping the entire click function in a separate function. None of these attempts made any difference.
JS:
function reply_click(clicked_id) {
var trys = [];
var title = document.getElementById("red-sub");
title.innerHTML = clicked_id;
$.getJSON("https://www.reddit.com/r/"+ clicked_id +"/.json", function(result){
for (var i = 0; i < result.data.children.length; i++) {
var imagesOnly = result.data.children[i].data;
if(imagesOnly.thumbnail !== 'self' && imagesOnly.post_hint === 'image'){
var items = result.data.children[i].data.url;
trys.push(items);
console.log(items);
var s = 0; // Start Point
function setImage(){
document.slide.src = trys[s];
}
setImage();
function changeImg(){
// Check If Index Is Under Max
if(s < trys.length - 1){
// Add 1 to Index
s++;
} else {
// Reset Back To O
s = 0;
}
setImage();
}
function changeBack(){
if(s < trys.length - trys.length + 1){
s = trys.length -1;
} else {
s--;
}
setImage();
}
}
}
console.log(trys);
document.getElementById ("btngo").addEventListener ("click", changeImg, true);
document.getElementById ("btnback").addEventListener ("click", changeBack, true);
});
}
document.getElementById("cats").addEventListener ("click", function(event)
{reply_click(event.target.id);;
});
document.getElementById("architecture").addEventListener ("click", function(event)
{reply_click(event.target.id);
});
HTML:
<body>
<div class="container">
<div class="entry-header">
<h1>subreddit slide shows</h1>
<p>Click the buttons below to browse through the latest photos of each noted subreddit.</p>
</div>
<div class="red-buttons">
<button id="cats">cats</button>
<button id="architecture">architecture</button>
</div>
<div class="main">
<div class="main_cat">
<div class="main_section">
<h2>r/<span id="red-sub">?????</span></h2>
<div class="img_container">
<img name="slide" class="cat_img" style=""
src="https://cdn.worldvectorlogo.com/logos/reddit-2.svg" />
</div>
<div class="button_base">
<button id="btnback"><</button>
<button id="btngo">></button>
</div>
</div>
</div>
</div>
</div>
</body>

jquery buttons don't work after their containing div is emptied and repopulated [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I'm making a game that generates four buttons with different hidden values. When my code runs the first time it works exactly as it should until I try to reset for a new game. After I empty the "crystals" div containing my four buttons, I generate four new ones but now they no longer work! How can I empty and repopulate a div with buttons that have click handlers that keep working? I'm new to coding so it's probably something dumb and easy.
I've tried substituting $('#crystals').empty with $('#crystals).html(""), per other articles on stack overflow, but I haven't found any resources specifically dealing with click handlers and the empty() function. I've also moved my functions around so they're inside the document.ready function as suggested by a classmate. I get the distinct impression that I'm asking the wrong questions.
var growCrystals = function() {
for (i = 0; i < 4; i++) {
var crystalButton = $("<button>");
scoreValue = Math.floor(Math.random() * 12) + 1;
console.log(scoreValue);
crystalButton.attr('class' , 'crystal-button');
crystalButton.attr('score-value' , scoreValue);
crystalButton.text('button');
console.log(crystalButton);
$('#crystals').append(crystalButton);
}
}
var newGame = function() {
targetNumber = pickTargetNumber();
totalScore = 0;
gameOver = false;
console.log($('#crystals'))
$('#results').empty();
$('#crystals').empty();
console.log($('#crystals'))
growCrystals();
console.log($('#crystals'))
updateGameboard();
console.log(gameOver);
}
// Game
$('document').ready(function() {
newGame();
$('.crystal-button').click(function() {
totalScore += parseInt($(this).attr('score-value'));
console.log("pushed ", $(this).attr('score-value'));
if (gameOver) {
newGame();
} else if (totalScore === targetNumber) {
// You win
wins++;
console.log("win ", wins);
updateGameboard();
$('#results').text('Player wins! Click any crystal to start a new game!')
gameOver = true;
} else if (totalScore > targetNumber) {
// You lose
losses++;
console.log("loss ", losses);
updateGameboard();
$('#results').text('Player loses! Click any crystal to start a new game!')
gameOver = true;
} else {
console.log("test loop occured")
updateGameboard();
}
})
});
<body class="d-flex flex-column h-100">
<div class="container">
<header>...
</header>
<section>
...
<div class="row">
<!-- <div class="col-md-2"></div> -->
<div class="col-md">
<div id="crystals"></div>
</div>
<!-- <div class="col-md-2"></div> -->
</div>
...
</section>
<footer class="footer mt-auto py-3">
...
</footer>
</div>
</body>
...
</html>
Use on
Instead of $('.crystal-button').click(function() {
use
$('#crystals').on('click', '.crystal-button' , function() {
This will assign the event handler to items with class .crystal-button in the #crystals element when the child elements are dynamically added. This works via event delegation

Loop with delay inside other loop

I'm trying to transform this loop that changes the value of a varible number of inputs:
$("#wrap input").each(function( index ) {
for( i = 10 ; i > 0 ; i--) {
$(this).val(i);
console.log( index + ": " + $(this).val() );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<input type="text">
<input type="text">
<input type="text">
</div>
I need to have a small delay between each iteration. I'm trying some variatons of this:
$("#wrap input").each(function( index ) {
var a = $(this);
var i = 10;
var loop = setInterval(function() {
a.val(i);
console.log( index + ": " + a.val() );
i--;
if(i==0) clearInterval( loop );
},1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<input type="text">
<input type="text">
<input type="text">
</div>
It doesn't work like I need.
I need to change the value in order, first input changes to 10 (delay) changes to 9 (delay)... second input changes to 10 (delay) changes to 9 (delay)... and so on. Hope you get the idea.
I'm thinking to assign them different ids via jQuery and then make a loop through each one separately, but I need a script as brief as possible.
Any changes to the structure have to be done with js.
The value update has to be in order
There must be a delay in each iteration
The code has to be as simple as possible
I'm a little stuck, I appreciate any hint.
Final update:
#acontell gave a perfect answer for the example I was dealing with in my question. Yet I realized why I didn't use next() since the begginnig: in the real project the inputs are not immediate siblings, they are each inside a couple of containers. Anyway the loop proposed by #acontell suits fine, I just had to put the elements in an array, like this:
var list = [];
$("#wrap input").each(function(index) {
list.push($(this));
});
var i = 10; // Countdown start
var n = 0; // Array index
var loop = setInterval(function() {
if (n > list.length - 1) {
clearInterval(loop);
} else {
list[n].val(i--);
if (i < 0) {
n++;
i = 10;
}
}
}, 100);
<div id="wrap">
<div><div><div><input type="text"></div></div></div>
<div><div><div><input type="text"></div></div></div>
<div><div><div><input type="text"></div></div></div>
<div><div><div><input type="text"></div></div></div>
<div><div><div><input type="text"></div></div></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm not really sure of what you're after, but if you want to wait for each counter (in each input) to finish and then start the next counter, a linked list comes to mind.
Jquery provides the method next that gets you the next sibling. That could help you to build the linked list. The iteration over the list could be done using an interval that would be cleared when there were no more siblings. Putting it all together:
var $element = $("#wrap input:first"),
countdownLimit = 10;
var loop = setInterval(function() {
if (!$element.length) {
clearInterval(loop);
} else {
$element.val(countdownLimit--);
if (countdownLimit < 0) {
$element = $element.next('input');
countdownLimit = 10;
}
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<input type="text">
<input type="text">
<input type="text">
</div>
There can be as many inputs as you like as long as they all are siblings.
Any time you need to have a delay in iterations, it makes sense to use a self-calling function instead of a loop.
function doStuff(data, i){
//do things here
console.log(i)
if(--i) setTimeout(function(){doStuff(data, i)}, 1000)
else nextStep(data)
}
function nextStep(data){
//after the loop ends, move to the next step of your code
}
doStuff([], 10)
Have you tried the equivalent of thread sleep?
var millisecondsToWait = 500;
setTimeout(function() {
// Whatever you want to do after the wait
}, millisecondsToWait);

How do I make a button disappear after a certain amount of clicks

I have a button is it possible to make it disappear if I click it say 5 times? need to know for a little project I'm working on!
any response is appreciated!
Use this Code
HTML:
<button type='button' id='button_test_clicks'>
Click me!
</button>
JavaScript:
(function(){
var counter=0; // counter clicks initialization
var button=document.getElementById('button_test_clicks'); //Our button
button.addEventListener("click",function(){ //add a click event to button
counter++; //incement the counter
console.log(a);
if(counter==5){
button.style.display = 'none'; //hide if the clicks reached to 5
}
});
})();
But whenever the page refresh happens counter sets to zero, to avoid refresh problems learn about localStorage in javascript.
Assign id to your button.
<Button id='myButton' onclick="myFunction()">
On every click of button, keep incrementing the counter (I think you know how to do it)
After the counter is reached,
document.getElementById("Your_button_id_here").style.visibility = "hidden";
<script>
var counter=0;
function myFunction() {
//increment counter
counter+=1;
if(counter>4)
document.getElementById("Your_button_id_here").style.visibility = "hidden"
}
</script>
However, I think disabling would be more proper:
document.getElementById("Your_button_id_here").disabled=true
You could have a simple script like this :
var nbClicks=0;
function btnOnClick(btn){
if(++nbClicks>5){btn.style.display='none';}
}
And use it like that :
<input type="button" onclick="btnOnClick(this)" value="Click me 6 times !">
On every click just increment a variable's value and after got desired number, hide it by css and js.
I made a small example with jQuery
var count = 0;
$("#b1").click(function() {
count++;
if (count >= 5) {
$("#b1").hide();
}
});
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<button id="b1">5 Clicks</button>
</body>
</html>

Multiple countdowns jQuery and organize them depending the time left

I want to create a website with multiple countdowns activated by a click, some of them have different time, others the same. I need to organize them depending the time left. When one finish I need to return it to his original countdown value, so you can click again.
To understand better (I don't need the effects, I made them only for the example): http://i.imgur.com/lvcwbqm.gif
I have this: http://jsfiddle.net/m19aojmu/
Each countdown works independently of the others.
HTML
<div class="element" id="el1"><b>Elm 1</b> <span class="timeout">10</span> segundos</div>
<div class="element" id="el2"><b>Elm 2</b> <span class="timeout">100</span> segundos</div>
<div class="element" id="el3"><b>Elm 3</b> <span class="timeout">5</span> segundos</div>
Javascript
function timer(selector) {
var self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
var interval = setInterval(function() {
sec--;
if (sec >= 0) {
self.find('span.timeout').text(sec);
} else {
clearInterval(interval);
}
}, 1000);
}
$("body").on('click', '.element', function() {
timer(this);
});
While each countdown have a different id (el1, el2, el3 ...) I don't know to detect which of them finished, therefore I don't know how to add a class when it start and end.
About the ubication, what should I do? Different classes for each location with position absolute?
I know it's a lot, but some help will be great.
Thank you very much.
Agusitn you code its like 95% correct, but you are setting the .text() into the sec variable wich is 0 or -1
Lets change the code a little bit
First lets take the actual value of the span DOM Element.
var actualTime = $('span.timeout').html();
console.log("the actual value when click is " + actualTime)
Later on the if statement we check when the actual span text its equal to 0
else if($(this).find('span').text() <= 0) {
console.log(sec)
var text = self.find('span.timeout').text(actualTime);
console.log(actualTime)
clearInterval(interval);
}
and when the .text() its === to 0, we set the actualTime variable to get back to the actual time.
here is the JsFiddle

Categories