Push numbers into array on click event - javascript

I'm trying to build a calculator and at this point, need to "collect" any numbers that get clicked in an array. Right now I'm unsure of where to build that array (should it be in a different function all together?). I think I'll need to use .push(), but know I need to use it on an array and am not sure where to define that. When I console.log(gridItems), clearly I get everything, but only want the numbers...
/*Calculator
function add(n, x) {
return n + x;
}
console.log(add(3, 8));
function subtract(n, x) {
return n - x;
}
console.log(subtract(3, 8));
function multiply(n, x) {
return n * x;
}
console.log(multiply(3, 8));
function divide(n, x) {
return n / x;
}
console.log(divide(3, 8));*/
// console.log number when button is clicked
function getValue(e){
var divValue = parseInt(e.target.textContent);
console.log(divValue);
}
function numberTrack() {
var gridItems = document.getElementsByClassName('grid');
for (var i = 0; i < gridItems.length; i ++) {
gridItems[i].onclick = getValue;
}
}
numberTrack();
#grid-container {
width: 200px;
}
.grid {
width: 50px;
height: 50px;
display: inline-block;
text-align: center;
}
.gray {
background-color: #ccc;
}
.pink {
background-color: pink;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<div id="grid-container" data-value="1">
<div class="grid gray">0</div>
<div class ="grid pink">1</div>
<div class="grid gray">2</div>
<div class ="grid pink">3</div>
<div class="grid gray">4</div>
<div class ="grid pink">5</div>
<div class="grid gray">6</div>
<div class ="grid pink">7</div>
<div class="grid gray">8</div>
<div class ="grid pink">9</div>
</div>
</head>
<body>
</body>
</html>

You can define it in global scope like this:
var clickedNumbers = []
function getValue(e) {
var divValue = parseInt(e.target.textContent);
clickedNumbers.push(divValue);
}
function numberTrack() {
var gridItems = document.getElementsByClassName('grid');
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].onclick = getValue;
}
}
numberTrack();
Then push clicked number to array clickedNumbers by clickedNumbers.push(divValue)

Related

How to show/hide a border using javascript

I have 10 square boxes with different colors. I'm trying to show a border for the square that the user clicks on, and hide the border of the previous square. So far I have this, but I somehow get Cannot read property 'style' of null. My idea is to hide the current box border, then show a border for the new box that the user clicks.
Here is the jsFiddle of what I want. However, it doesn't seem to work. I can only use Javascript and can't use JQuery
https://jsfiddle.net/5op0d7zs/7/
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
}
box1.onclick = function() { changeColor("#e6e2cf",1); }
box2.onclick = function() { changeColor("#dbcaac",2); }
box3.onclick = function() { changeColor("#c9cbb3",3); }
box4.onclick = function() { changeColor("#bbc9ca",4); }
box5.onclick = function() { changeColor("#a6a5b5",5); }
box6.onclick = function() { changeColor("#b5a6ab",6); }
box7.onclick = function() { changeColor("#eccfcf",7); }
box8.onclick = function() { changeColor("#eceeeb",8); }
box9.onclick = function() { changeColor("#bab9b5",9); }
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
You don't need to call the changeColor twice. Second thing You can do what you want in less code.
See this working example here.
You can check the updated fiddle here
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
document.getElementById("box" + currentBoxNum).style.borderColor = "black";
}
document.getElementById("box1").addEventListener("click", function(){ changeColor("#e6e2cf", 1); });
document.getElementById("box2").addEventListener("click", function(){ changeColor("#dbcaac", 2); });
document.getElementById("box3").addEventListener("click", function(){ changeColor("#c9cbb3", 3); });
document.getElementById("box4").addEventListener("click", function(){ changeColor("#bbc9ca", 4); });
document.getElementById("box5").addEventListener("click", function(){ changeColor("#a6a5b5", 5); });
document.getElementById("box6").addEventListener("click", function(){ changeColor("#b5a6ab", 6); });
document.getElementById("box7").addEventListener("click", function(){ changeColor("#eccfcf", 7); });
document.getElementById("box8").addEventListener("click", function(){ changeColor("#eceeeb", 8); });
document.getElementById("box9").addEventListener("click", function(){ changeColor("#bab9b5", 9); });
#box1 {
background-color: #e6e2cf;
border: 2px solid black;
}
#box2 {
background-color: #dbcaac;
}
#box3 {
background-color: #c9cbb3;
}
#box4 {
background-color: #bbc9ca;
}
#box5 {
background-color: #a6a5b5;
}
#box6 {
background-color: #b5a6ab;
}
#box7 {
background-color: #eccfcf;
}
#box8 {
background-color: #eceeeb;
}
#box9 {
background-color: #bab9b5;
}
.pad {
margin: 10px;
}
.colors {
display: flex;
flex-wrap: wrap;
}
.colors>div {
width: 50px;
margin: 10px;
height: 50px;
}
<!-- This is a static file -->
<!-- served from your routes in server.js -->
<!DOCTYPE html>
<html>
<head>
<title>Show me!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./reset.css">
<link rel="stylesheet" href="./style.css">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Homemade+Apple|Indie+Flower|Long+Cang&display=swap" rel="stylesheet">
</head>
<body>
<main>
<div class="pad">
<h2 class="choose_pad">Choose your color</h2>
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
</div>
</main>
<footer>
<p class="msg">
Made on Glitch!
</p>
<!-- adds the glitch button at the bottom -->
<div class="glitchButton"></div>
<script src="https://button.glitch.me/button.js"></script>
<script src="./script.js"></script>
</footer>
</body>
</html>
You're calling
document.getElementById("cb").style.backgroundColor = background;
There is no element with an id of "cb".
Update your code to properly reference the id of the element you wish to change the background color for.
Missing line: document.getElementById("box" + currentBoxNum).style. borderColor = background;
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
document.getElementById("box" + currentBoxNum).style. borderColor = background;
}
box1.onclick = function() { changeColor("#e6e2cf",1); }
box2.onclick = function() { changeColor("#dbcaac",2); }
box3.onclick = function() { changeColor("#c9cbb3",3); }
box4.onclick = function() { changeColor("#bbc9ca",4); }
box5.onclick = function() { changeColor("#a6a5b5",5); }
box6.onclick = function() { changeColor("#b5a6ab",6); }
box7.onclick = function() { changeColor("#eccfcf",7); }
box8.onclick = function() { changeColor("#eceeeb",8); }
box9.onclick = function() { changeColor("#bab9b5",9); }
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
You can change you changeColor method as below
function changeColor(background, boxNum) {
$('.colors div').css('border', 'none'); // This will remove borders from all boxes
document.getElementById("box" + boxNum).style.borderStyle = "solid";
document.getElementById("box" + boxNum).style.borderColor = background;
}
Since this method is using jQuery, please include the jQuery in your html as below,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Also, this is just adding the border color not background color. If you want to add the background color as well you can add the following statement in changeColor function
document.getElementById("box" + boxNum).style.backgroundColor = background;

Why does one calculation for my onClick get applied to all elements that I'm looping through

Currently doing some exercise for CSS/Javascript animation. I'm attempting to make a Carousel slider from scratch.. I have 4 divs with 550px in width nested in a wrapper of 2200px, which is then nested in a 550px wrapper with overflow hidden.
I then created 4 LI's that I want to make clickable so that it'll translate the wrapper -550*I degrees for every LI.
I performed a queryselectorall to get all the li's, looped through it with a for loop, and created a function that should apply onclick functionality for each LI button.
The issue that I'm running into is that the first calculation of this transform property is applied to all LI's (the 550 * i for [1] [2] and [3] aren't applied).
Here's the HTML that I'm currently using.
<div id="container">
<div id="wrapper">
<div id="itemOne" >
</div>
<div id="itemTwo">
</div>
<div id="itemThree">
</div>
<div id="itemFour">
</div>
</div>
</div>
<ul>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
</ul>
The Javascript
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll(".button");
for(var i = 0; i < buttons.length; i++){
var curBut = buttons[i];
curBut.addEventListener("click", function(){
wrapper.style[transformProperty] = 'translate3d(-'+((0-i) * 550) +'px,0,0'
})
console.log(((0-i) * 550));
}
console.log(buttons);
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++){
if(typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
If anyone could explain why the function isn't applying the different changes for the wrapper for each LI, that'd be great! Thanks!!
The global variable i is not copied into each listener, it's shared between the listeners. When you click a button, i is already set to its final value which is 4. As a possible workaround you could override the global variable with a local variable, and get the index on click using indexOf :
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
var curBut = buttons[i];
curBut.addEventListener("click", function() {
var i = Array.prototype.indexOf.call(buttons, this);
wrapper.style[transformProperty] = 'translate3d(-' + (i * 260) + 'px,0,0)';
});
}
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
#container {
overflow: hidden;
background: gray;
margin-bottom: 1em;
width: 260px;
height: 100px;
}
#wrapper {
width: calc(4 * 260px);
height: 100px;
}
#wrapper div {
padding: 0 1em;
width: calc(260px - 2em);
line-height: 100px;
height: 100px;
float: left;
color: white;
font-size: 3em;
font-weight: bold;
text-align: center;
}
<div id="container">
<div id="wrapper">
<div id="itemOne">1</div>
<div id="itemTwo">2</div>
<div id="itemThree">3</div>
<div id="itemFour">4</div>
</div>
</div>
<div>
<button type="button">button 1</button>
<button type="button">button 2</button>
<button type="button">button 3</button>
<button type="button">button 4</button>
</div>

How can I update attributes with jQuery?

$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`

Having trouble restarting logic Tic Tac Toe game (JavaScript)

I am having trouble to look where the problem is.
I was able to create the game board and I will be implementing AI soon.
For now, I need to make it work so that everytime the game is over, it will restart a new one and resume.
However when it reaches to that point, it stops working.
From my what I've read, I may not be binding the events correctly, but I am still left puzzled.
Can anyone pinpoint what is wrong with my code?
$(document).ready(function(){
var human;
var computer;
var board = new Board()
var game;
function Human(symbol){
this.name = "Player",
this.symbol = symbol;
}
function Computer(symbol){
this.name = "Computer",
this.symbol = symbol;
}
//Modal opens when page is rendered. User can choose symbol
$("#myModal").modal()
$("#xPlayer").on('click',function(){
human = new Human("X");
computer = new Computer("O");
board.initalize();
game = new Game(human)
game.play();
})
$("#oPlayer").on('click',function(){
human = new Human("O")
computer = new Computer("X");
board.initalize();
game = new Game(computer)
game.play();
})
//Board constuctor
function Board(){
this.board = []
this.status = "";
}
//method calls for an empty board filled with "E"
Board.prototype.initalize = function(){
$("td p").empty()
this.board = ["E","E","E","E","E","E","E","E","E"]
this.status = "New Game";
}
//return true if there is a win. Otherwise, false
Board.prototype.win = function(){
var B = this.board;
//check row
for (var i = 0; i <= 6; i = i + 3){
if (B[i] !== "E" && (B[i] === B[i+1]) && (B[i+1] === B[i+2])){
board.status = "Winner is: " + game.currentPlayer.name
return true
}
}
//check column
for (var i = 0; i <= 2 ; i++ ){
if (B[i] !== "E" && (B[i] === B[i+3]) && (B[i+3] === B[i+6])){
board.status = "Winner is: " + game.currentPlayer.name
return true
}
}
//check diagonal
for(var i = 0, j = 4; i <= 2 ; i = i + 2, j = j - 2) {
if(B[i] !== "E" && (B[i] == B[i + j]) && (B[i + j] === B[i + 2 * j]) ) {
board.status = "Winner is: " + game.currentPlayer.name
return true;
}
}
return false
}
//checks if the current status is draw. If so, updates the status to "Draw"
Board.prototype.draw = function(){
//checks if the board itself is draw
for(var i = 0; i < this.board.length ; i++){
if (this.board[i] === "E"){
return false;
}
}
board.status = "Draw!"
return true;
}
//method returns array of indexes that are not empty cells in the board
Board.prototype.available = function(){
var B = this.board;
var indexes = [];
for (var i = 0; i < B.length ; i ++){
if (B[i] === "E"){
indexes.push(i)
}
}
return indexes;
}
//checks first if the User Input is valid or not
Board.prototype.validMove = function(position){
var availableCells = this.available();
return availableCells.includes(position);
}
//updates the board when using jQuery click
//it will render the webpage by prototype_writeBoard
Board.prototype.updateBoard = function(position,playerInput) {
var availableCells = this.available();
if (availableCells.includes(position)){
this.board[position] = playerInput
}
};
function Game(firstPlayer){
this.currentPlayer = firstPlayer;
this.over = false;
this.win = "";
}
Game.prototype.switchPlayer = function(){
this.currentPlayer = (this.currentPlayer === human) ? computer : human
}
Game.prototype.play = function(){
$("td").click(function(){
var position = $(this).attr("id");
var positionNumber = parseInt(position.slice(4,5))
// This here renders to the board and updates board.board
if(board.validMove(positionNumber)){
//Checks if the move is valid. If it is, append it.
//Otherwise, alert the user that it is taken
$(this).find("p").append(game.currentPlayer.symbol)
board.updateBoard(positionNumber, game.currentPlayer.symbol)
//Check if it the game is over or draw
//If either is true, play new game
if (board.win() || board.draw()){
alert(board.status)
game.restart();
}
game.switchPlayer();
}else{
alert("Already taken")
}
})
}
Game.prototype.restart = function(){
board.initalize();
game.play()
}
})
body {
background: skyblue; }
#tictactoe {
max-width: 700px;
min-height: 300px;
margin: 68px auto;
display: flex;
width: 100%; }
#tictactoe table {
width: 100%;
font-size: 65px;
text-align: center;
vertical-align: middle;
table-layout: fixed; }
td {
height: 115px;
color: #101935;
background: #F2FDFF;
border: 5px solid #DBCBD8;
border-radius: 12px;
cursor: pointer;
transition: background 0.5s ease-out, color 0.5s ease-out; }
td:hover {
background: #564787;
color: #F2FDFF; }
.modal-dialog {
text-align: center; }
.modal-dialog .modal-footer {
text-align: center; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TicTacToe FCC</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="css/styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="tictactoe">
<table id="game-board">
<tbody>
<tr id="row1">
<td id="cell0"><p></p></td>
<td id="cell1"><p></p></td>
<td id="cell2"><p></p></td>
</tr>
<tr id="row2">
<td id="cell3"><p></p></td>
<td id="cell4"><p></p></td>
<td id="cell5"><p></p></td>
</tr>
<tr id="row3">
<td id="cell6"><p></p></td>
<td id="cell7"><p></p></td>
<td id="cell8"><p></p></td>
</tr>
</tbody>
</table>
</div>
<!--Modal Window -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Choose your character!</h4>
</div>
<div class="modal-body">
<p>Have fun!</p>
</div>
<div class="modal-footer">
<button type="button" id="xPlayer" class="btn btn-default" data-dismiss="modal">X</button>
<button type="button" id="oPlayer" class="btn btn-default" data-dismiss="modal">O</button>
</div>
</div>
</div>
</div>
</body>
<script src="js/javascript.js" type="text/javascript"></script>
</html>
In Game.play you are binding to the onclick of the td element. Then in Game.restart you are calling Game.play which is binding to the click event again. Since you are already calling Game.play when you setup the players there is no need to call it in Game.restart since it is still bound to the click event
Game.prototype.restart = function(){
board.initalize();
/* delete-me game.play() */
}

How to add data locally and add value by its id?

<!DOCTYPE HTML>
<html>
<head>
<title>HTML5 localStorage (name/value item pairs) demo</title>
<style >
td, th {
font-family: monospace;
padding: 4px;
background-color: #ccc;
}
#hoge {
border: 1px dotted blue;
padding: 6px;
background-color: #ccc;
margin-right: 50%;
}
#items_table {
border: 1px dotted blue;
padding: 6px;
margin-top: 12px;
margin-right: 50%;
}
#items_table h2 {
font-size: 18px;
margin-top: 0px;
font-family: sans-serif;
}
label {
vertical-align: top;
}
</style>
</head>
<body onload="doShowAll()">
<h1>HTML5 localStorage (name/value item pairs) demo</h1>
<form name=editor>
<div id="hoge">
<p>
<label>Value: <textarea name=data cols=41 rows=10></textarea></label>
</p>
<p>
<label>Name: <input name=name></label>
<input type=button value="getItem()" onclick="doGetItem()">
<input type=button value="setItem()" onclick="doSetItem()">
<input type=button value="removeItem()" onclick="doRemoveItem()">
</p>
</div>
<div id="items_table">
<h2>Items</h2>
<table id=pairs></table>
<p>
<label><input type=button value="clear()" onclick="doClear()"> <i>* clear() removes all items</i></label>
</p>
</div>
<script>
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
function doGetItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.getItem(name);
doShowAll();
}
function doRemoveItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.removeItem(name);
doShowAll();
}
function doClear() {
localStorage.clear();
doShowAll();
}
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var i=0;
for (i=0; i<=localStorage.length-1; i++) {
key = localStorage.key(i);
pairs += "<tr><td>"+key+"</td>\n<td>"+localStorage.getItem(key)+"</td></tr>\n";
}
if (pairs == "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
</script>
</form>
</body>
</html>
Hi friends,
I wants to locally save the data,now I am able to save the data locally by the code.even if I give the same name the value is getting added and saved locally.but the name should be shown in order of high value to low(example: Ram 20,Renu 18,green 2 like wise...).so how to do this?
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
To display them in descending order:
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var userArray = [];
for (var i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
userArray.push({name:key, value:parseInt(localStorage.getItem(key))});
}
userArray.sort(function(a, b){
return b.value - a.value;
});
userArray.forEach(function(user){
pairs += "<tr><td>" + user.name + "</td>\n<td>" + user.value + "</td></tr>\n";
});
if (pairs === "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
For what I can see in your code, you're just replacing the value, you need to get the existent value from the localStorage first, append to it the new one and then asign the result to the localStorage.

Categories

Resources