Storing class names in variable - javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta washere="fgras">
<title>Mesure de Distance - Page 1</title>
<style type="text/css">
<!-- ****************** Table ****************** -->
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: center;
}
tr:nth-child(even) {
background-color: #ccc;
}
tr:nth-child(odd) {
background-color: #fff;
}
th {
background-color: darkslategray;
color: white;
}
body{
font-family:arial;
}
.valHP {
background-color: #A0A0A0;
}
.valError {
background-color: #FF00FF;
}
.valInsideGood {
color: #00A000;
}
.valInsideBad {
color: #FF0000;
}
</style>
<script type="text/javascript">
var requestNumber=0;
var value1Node = null;
var value2Node = null;
function onData(e, xhr){
try{
console.log("onData.event =",e);
console.log("onData.xhr =",xhr);
var data = xhr.responseText;
console.log("data =",data);
data = data.split("|");
var value1 = Number(data[1]);
var value2 = Number(data[2]);
value1Node.textContent = value1;
value2Node.textContent = value2;
if(value1==0){
value1Node.className="valHP";
value1Node.textContent="--";
}else if(value1>=26 && value1<=28){
value1Node.className="valInsideBad";
}else if(value1>28 && value1<=34){
value1Node.className="valInsideGood";
}else{
value1Node.className="valError";
value1Node.textContent="err";
}
}finally{
setTimeout(refreshData,200);
}
}
function refreshData(){
requestNumber++;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", (function(e){return onData(e, xhr);}));
xhr.open("GET", "data.html?t="+requestNumber); //t pour un nom de page unique et éviter le cache
xhr.send();
}
function onPageLoad(){
value1Node = document.getElementById("val1");
refreshData();
}
</script>
</head>
<body onload="onPageLoad()">
<div class="table100-body js-pscroll">
<table style="width:50%">
<thead>
<tr class="row100 head">
<th class="cell100 column1">Colonne1</th>
<th class="cell100 column2">Colonne2</th>
<th class="cell100 column3">Colonne3</th>
<th class="cell100 column4">Colonne4</th>
<th class="cell100 column5">Colonne5</th>
</tr>
</thead>
<tbody>
<tr class="row100-body">
<td class="cellColumn"> <span id="val1"></span></td>
<td class="cellColumn"> Capteur 1= </td>
<td class="cellColumn"> Distance_Capt_1</td>
<td class="cellColumn"> Distance_Capt_1</td>
<td class="cellColumn"> Distance_Capt_1</td>
</tr>
</tbody>
</table>
</div>
</body>
I'm trying to display a data that i receive from a hardware on a web page in a table.
Based on what range my received datas are in, I need to display them with red and green colors.
I have defined 4 classes using CSS.
In my html part, inside a table i want to assign classes to td blocks, but my classes are stored in a variabale (value1Node.className)
I tried td class=value1Node.className and it doesn't work.
I also put value1Node.className in "" and '' and it didn't work.
how can i do this?
(All other parts of code works just fine)
data is stored in value1 and i have 3 ifs in javascript:
if (value1 == 0) {
value1Node.className = "valHP";
value1Node.textContent = "Out of Range";
} else if (value1 >= 26 && value1 <= 28) {
value1Node.className = "valInsideBad";
} else if (value1 > 28 && value1 <= 34) {
value1Node.className = "valInsideGood";
} else {
value1Node.className = "valError";
value1Node.textContent = "err";
}
.valHP {
background-color: #A0A0A0;
}
.valError {
background-color: #FF00FF;
}
.valInsideGood {
color: #00A000;
}
.valInsideBad {
color: #FF0000;
}

HTML5 custom-data attributes are designed for this purpose.
Instead of:
class="valHP"
class="valError"
class="valInsideGood"
class="valInsideBad"
You can have:
data-my-value="HP"
data-my-value="Error"
data-my-value="InsideGood"
data-my-value="InsideBad"
and then in your CSS you can have:
[data-my-value="HP"] {
background-color: #A0A0A0;
}
[data-my-value="Error"] {
background-color: #FF00FF;
}
[data-my-value="InsideGood"] {
color: #00A000;
}
[data-my-value="InsideBad"] {
color: #FF0000;
}
Then, in your javascript, you can have:
if (value1 === 0) {
value1Node.setAttribute('data-my-value', 'valHP');
value1Node.textContent = "Out of Range";
} else if (value1 >= 26 && value1 <= 28) {
value1Node.setAttribute('data-my-value', 'InsideBad');
} else if (value1 > 28 && value1 <= 34) {
value1Node.setAttribute('data-my-value', 'InsideGood');
} else {
value1Node.setAttribute('data-my-value', 'Error');
value1Node.textContent = "err";
}
If at any point you wish to query the value of data-value, you can use dataset:
value1Node.dataset.myValue // returns data-my-value
You can also directly set each value via dataset:
value1Node.dataset.myValue = 'InsideGood'; // Now: data-my-value="InsideGood"
Knowing this, you can now script the following:
if (value1 === 0) {
value1Node.data.myValue = 'valHP';
value1Node.textContent = "Out of Range";
} else if (value1 >= 26 && value1 <= 28) {
value1Node.data.myValue = 'InsideBad';
} else if (value1 > 28 && value1 <= 34) {
value1Node.data.myValue = 'InsideGood';
} else {
value1Node.data.myValue = 'Error';
value1Node.textContent = "err";
}
Further Reading:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
https://hacks.mozilla.org/2012/10/using-data-attributes-in-javascript-and-css/

Related

Why clock time is not being shown?

I am trying to make a simple task manager. I added a clock at the top of the page and after a few check list I added few codes that will show me how much time of the day is left. I got that from my question: How can I code a clock to show me that how much time is left of the day?
I took the second answer and it was working separately as I wanted. But after I inserted that code to my main code the time is not being shown. It's just blank.
Here's my code:
<html lang="en">
<head>
<title>Task Achievement</title>
<link href="https://fonts.googleapis.com/css2?family=Concert+One&display=swap" rel="stylesheet">
<script>
function myFunction(item) {
if (item.checked) {
item.parentNode.style.backgroundColor = "#8db600";
} else {
item.parentNode.style.backgroundColor = "transparent";
}
}
</script>
<style>
table { border:solid 1px #8db600; }
body {
background-color: #7ef9ff;
}
#import url('');
#clock {
margin: auto;
width: 300px;
height: 50px ;
background-color: black;
font-family: "Concert One";
color: #7ef9ff;
font-size: 48px;
text-align: center;
padding: 5px 5px 5px 5px;
}
#task {
width: 300px;
margin: auto;
color: #7ef9ff;
background-color: black;
font-family: "Concert One";
}
#tab {
font-family: "Concert One";
}
</style>
</head>
<body>
<div id="clock"></div>
<script>function currentTime() {
var date = new Date(); /* creating object of Date class */
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
if (hour > 12){
hour = hour - 12;
}
else{
hour = hour;
}
hour = updateTime(hour);
min = updateTime(min);
sec = updateTime(sec);
document.getElementById("clock").innerText = hour + " : " + min + " : " + sec; /* adding time to the div */
var t = setTimeout(function(){ currentTime() }, 1000); /* setting timer */
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
}
else {
return k;
}
}
currentTime(); /* calling currentTime() function to initiate the process */</script>
<div id="task">
<h4 align = 'center'>Today's Accomplishments</h4>
</div>
<div id="tab">
<table align="center" #8db600" CELLSPACING=0>
<tr>
<td id="box">
Vocab<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td id="box">
SAT-Math<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
SAT-Reading<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
SAT-Writing<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
Chemistry<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
Math<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
</tr>
</table>
</div>
<div id="clock"></div>
<script>function currentTime() {
var toDate=new Date();
var tomorrow=new Date();
tomorrow.setHours(24,0,0,0);
var diffMS=tomorrow.getTime()/1000-toDate.getTime()/1000;
var diffHr=Math.floor(diffMS/3600);
diffMS=diffMS-diffHr*3600;
var diffMi=Math.floor(diffMS/60);
diffMS=diffMS-diffMi*60;
var diffS=Math.floor(diffMS);
var result=((diffHr<10)?"0"+diffHr:diffHr);
result+=" : "+((diffMi<10)?"0"+diffMi:diffMi);
result+=" : "+((diffS<10)?"0"+diffS:diffS);
document.getElementById("clock").innerText = result; /* adding time to the div */
var t = setTimeout(function(){ currentTime() }, 1000); /* setting timer */
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
}
else {
return k;
}
}
currentTime(); /* calling currentTime() function to initiate the process */
</body>```
I think I understand. You want 2 clocks, the first one showing NOW time and the second one showing time left in the day, am I right?.
In that case, the two div can not have the same ID and the function can not have the same name.
<html lang="en">
<head>
<title>Task Achievement</title>
<link href="https://fonts.googleapis.com/css2?family=Concert+One&display=swap" rel="stylesheet">
<script>
function myFunction(item) {
if (item.checked) {
item.parentNode.style.backgroundColor = "#8db600";
} else {
item.parentNode.style.backgroundColor = "transparent";
}
}
</script>
<style>
table {
border: solid 1px #8db600;
}
body {
background-color: #7ef9ff;
}
#import url('');
#clock,
#clock-left {
margin: auto;
width: 300px;
height: 50px;
background-color: black;
font-family: "Concert One";
color: #7ef9ff;
font-size: 48px;
text-align: center;
padding: 5px 5px 5px 5px;
}
#task {
width: 300px;
margin: auto;
color: #7ef9ff;
background-color: black;
font-family: "Concert One";
}
#tab {
font-family: "Concert One";
}
</style>
</head>
<body>
<div id="clock"></div>
<script>
function currentTime() {
var date = new Date(); /* creating object of Date class */
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
if (hour > 12) {
hour = hour - 12;
} else {
hour = hour;
}
hour = updateTime(hour);
min = updateTime(min);
sec = updateTime(sec);
document.getElementById("clock").innerText = hour + " : " + min + " : " + sec; /* adding time to the div */
var t = setTimeout(function() {
currentTime()
}, 1000); /* setting timer */
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
} else {
return k;
}
}
currentTime(); /* calling currentTime() function to initiate the process */
</script>
<div id="task">
<h4 align='center'>Today's Accomplishments</h4>
</div>
<div id="tab">
<table align="center" #8db600 CELLSPACING=0>
<tr>
<td id="box">
Vocab<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td id="box">
SAT-Math<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
SAT-Reading<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
SAT-Writing<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
Chemistry<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
Math<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
</tr>
</table>
</div>
<div id="clock-left"></div>
<script>
function timeLeft() {
var toDate = new Date();
var tomorrow = new Date();
tomorrow.setHours(24, 0, 0, 0);
var diffMS = tomorrow.getTime() / 1000 - toDate.getTime() / 1000;
var diffHr = Math.floor(diffMS / 3600);
diffMS = diffMS - diffHr * 3600;
var diffMi = Math.floor(diffMS / 60);
diffMS = diffMS - diffMi * 60;
var diffS = Math.floor(diffMS);
var result = ((diffHr < 10) ? "0" + diffHr : diffHr);
result += " : " + ((diffMi < 10) ? "0" + diffMi : diffMi);
result += " : " + ((diffS < 10) ? "0" + diffS : diffS);
document.getElementById("clock-left").innerText = result; /* adding time to the div */
var t = setTimeout(function() {
timeLeft()
}, 1000); /* setting timer */
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
} else {
return k;
}
}
timeLeft(); /* calling currentTime() function to initiate the process */
</script>
</body>
Your table is not being rendered properly because you are declaring it like this: <table align="center" #8db600" CELLSPACING=0>.
Is "#8db600"" supposed to be an attribute or an attribute value? Either way, you didn't finish either declaration, so it becomes a syntax error. Remove the stray "#8db600"".
Additionally, remove that duplicate declaration of the currentTime() function which is superfluous.
<html lang="en">
<head>
<title>Task Achievement</title>
<link href="https://fonts.googleapis.com/css2?family=Concert+One&display=swap" rel="stylesheet">
<script>
function myFunction(item) {
if (item.checked) {
item.parentNode.style.backgroundColor = "#8db600";
} else {
item.parentNode.style.backgroundColor = "transparent";
}
}
</script>
<style>
table {
border: solid 1px #8db600;
}
body {
background-color: #7ef9ff;
}
#import url('');
#clock {
margin: auto;
width: 300px;
height: 50px;
background-color: black;
font-family: "Concert One";
color: #7ef9ff;
font-size: 48px;
text-align: center;
padding: 5px 5px 5px 5px;
}
#task {
width: 300px;
margin: auto;
color: #7ef9ff;
background-color: black;
font-family: "Concert One";
}
#tab {
font-family: "Concert One";
}
</style>
</head>
<body>
<div id="clock"></div>
<script>
function currentTime() {
var date = new Date(); /* creating object of Date class */
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
if (hour > 12) {
hour = hour - 12;
} else {
hour = hour;
}
hour = updateTime(hour);
min = updateTime(min);
sec = updateTime(sec);
document.getElementById("clock").innerText = hour + " : " + min + " : " + sec; /* adding time to the div */
var t = setTimeout(function() {
currentTime()
}, 1000); /* setting timer */
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
} else {
return k;
}
}
currentTime(); /* calling currentTime() function to initiate the process */
</script>
<div id="task">
<h4 align='center'>Today's Accomplishments</h4>
</div>
<div id="tab">
<table align="center">
<tr>
<td id="box">
Vocab<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td id="box">
SAT-Math<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
SAT-Reading<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
SAT-Writing<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
Chemistry<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
<td class="box">
Math<input type="checkbox" name="block" id="block" onclick="myFunction(this)">
</td>
</tr>
</table>
</div>
<div id="clock"></div>
</body>
</html>

after filtering input in contenteditable/input to put caret where it was

I have a contenteditable element what I update/filter with javascript. After updating the textcontent the but the caret always goes back to the beginning. A want to make to work like the input element.
I set up a demo:
test1 - contenteditable element
test2 - input element
In this example I have a function what enable to insert only numbers, if you insert other characters nothing will show.
After entering some numbers to the contenteditable and inserting a NOT number, then the cursor (caret) goes to the start. In case of input element the cursor goes to the end.
How to achieve that, to remain the cursor to the position where it was?
(pure javascript)
function onlyNumber(element) {
const invalidChars = /\D/g;
ob = element.target;
if (element.target.nodeName == "INPUT") {
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
} else if (element.target.nodeName == "TD") {
if (invalidChars.test(ob.textContent)) {
ob.textContent = ob.textContent.replace(invalidChars, "");
}
}
}
document.getElementById("test1").addEventListener("input", function(event) {
onlyNumber(event);
})
document.getElementById("test2").addEventListener("input", function(event) {
onlyNumber(event);
})
#test1 {
border: 1px solid gray;
padding: 5px;
width: 100px;
}
#test2 {
margin-top: 15px;
}
<table class="table">
<tbody>
<tr>
<td id="test1" contenteditable="true"></td>
</tr>
</tbody>
</table>
<input id="test2" />
You could use the keydown event, and prevent all but numbers and arrows/delete/backspace.
Stack snippet
function onlyNumber(element) {
const invalidChars = /\D/g;
ob = element.target;
if (element.target.nodeName == "INPUT") {
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
} else if (element.target.nodeName == "TD") {
if (invalidChars.test(ob.textContent)) {
ob.textContent = ob.textContent.replace(invalidChars, "");
}
}
}
document.getElementById("test1").addEventListener("keydown", function(event) {
if ((event.keyCode < 58 && event.keyCode > 47) ||
(event.keyCode < 41 && event.keyCode > 36) ||
event.keyCode == 8 || event.keyCode == 46) {
return true;
}
event.preventDefault();
})
document.getElementById("test2").addEventListener("input", function(event) {
onlyNumber(event);
})
#test1 {
border: 1px solid gray;
padding: 5px;
width: 100px;
}
#test2 {
margin-top: 15px;
}
<table class="table">
<tbody>
<tr>
<td id="test1" contenteditable="true"></td>
</tr>
</tbody>
</table>
<input id="test2" />
Another option would be to re-position the cursor:
How to move cursor to end of contenteditable entity
How to track caret/cursor in contenteditable?

Javascript Cell Filling

I'm trying to fill an HTML table with some values from my JS code.
The first few lines work, but my function doesn't.
Does anyone know why? I've included my code below.
function set(id,num) {
document.getElementById(id).innerHTML = num;
}
var num1 = set("1.4", 55); //ok
var num2 = set("1.6", 56); //ok
var num3 = set("1.12", 57); //ok
function addition() { //notok
//var n1 = document.getElementById("1.4").innerHTML;
//var n2 = document.getElementById("1.6").innerHTML;
//var n3 = document.getElementById("1.12").innerHTML;
//document.getElementById("1.14").innerHTML = parseInt(n1) + parseInt(n2) + parseInt(n3);
document.getElementById("1.14").innerHTML = 55 + 56 + 57;
}
body {
background-color: white;
}
table {
font-size: 15px;
border-collapse: collapse;
border: solid black 1px;
border-radius: 6px;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
}
td, th {
border: solid black 1px;
padding: 10px;
}
.theader {
background-color: rgb(254, 102, 0);
}
th:first-child{
border-top: none;
}
td {
text-align:center;
}
td:first-child, th:first-child {
font-weight: bold;
}
h1 {
margin-top: 150px;
text-align: center;
color: black;
}
tr { background-color: white}
.change { background-color: black; color:white }
.normal { background-color: white }
.notchange{ background-color: white }
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
</head>
<body>
<h1>Test</h1>
<table>
<tr class="normal" onmouseover="this.className='change'" onmouseout="this.className='notchange'">
<td>Row1</td>
<td id="1.1">11</td>
<td id="1.2">11</td>
<td id="1.3">12</td>
<td id="1.4"></td>
<td id="1.5">14</td>
<td id="1.6"></td>
<td id="1.7">16</td>
<td id="1.8">17</td>
<td id="1.9">18</td>
<td id="1.10">19</td>
<td id="1.11">20</td>
<td id="1.12"></td>
<td id="1.13">22</td>
<td id="1.14"></td>
</tr>
...........
</table>
<script type="text/javascript" src="MyJavaScript1.js"></script>
</body>
</html>
I am writing just a table with JS, ("1.4","1.6","1.12") cells filling properly but i can not fill the cell "1.14".
You never actually invoke the function so it doesn't run.
Change your code to look like this:
function set(id,num) {
document.getElementById(id).innerHTML = num;
}
var num1 = set("1.4", 55); //ok
var num2 = set("1.6", 56); //ok
var num3 = set("1.12", 57); //ok
function addition() { //notok
document.getElementById("1.14").innerHTML = 55 + 56 + 57;
}
// added this line:
addition();
I added the last line (and removed commented lines) which will invoke the method (thus running the code inside) and I moved the function to the top of the file. While not neccessary to move the function thanks to function hoisting I feel it's good practice to declare a function before invoking it.
Additional note
You're assigning the result of the set function to a variable with the following line:
var num1 = set("1.4", 55); //ok
You don't have to do this. You can just call set("1.4", 55).
======== OLD ANSWER BELOW ==========
You're using getElementById and .valueOf wrong. getElementById
refers to a HTML element. For example:
getElementById("cell1") would pick the element which looks like:
<td id="cell1"></td>
.valueOf returns the primitive value of a String object, for example:
var str = "Hello World!";
var res = str.valueOf();
console.log(res); // prints: Hello World!
So assuming your html looks like this:
<table>
<tr>
<td id="cell1"></td>
<td id="cell2"></td>
<td id="cell3"></td>
</tr>
</table>
The Javascript code to fill the cell's would look something like
this::
document.getElementById("cell1").innerHTML = "1.4";
document.getElementById("cell2").innerHTML = "1.6";
document.getElementById("cell3").innerHTML = "1.12";
function addition() { //OK
var n1 = document.getElementById("1.4").innerHTML;
var n2 = document.getElementById("1.6").innerHTML;
var n3 = document.getElementById("1.12").innerHTML;
document.getElementById("1.14").innerHTML = parseInt(n1) + parseInt(n2) + parseInt(n3);
}
addition();
And it works. My fault. I deleted to function call and forget to write again.

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