I really dont know what is happening
I recently made this flask application and came across this error where my buttons don't works for other html table rows that are there and i don't know why. I tried my best to solve it but sadly couldn't. If someone can help me i would really appreciate it
HERE IS THE HTML CODE
<html lang="en">
<head>
<title>Timer</title>
<style>
body{
background-color: khaki;
}
h1{
font-family: monospace;
font-size:5em;
transform: translate(500px, 10px);
}
/*
h4{
font-family:monospace;
font-size: 2em;
transform: translate(700px, 10px);
} */
div.container input[type=submit] {
background-color:khaki;
border-radius: 1.8em 1.8em 1.8em;
text-transform: uppercase;
color: black;
border: none;
font-size: 2em;
font-family: monospace;
transform: translate(500px, 10px);
}
div.container input[type=text]{
transform: translate(500px, 10px);
}
table th{
text-align: left;
padding: 4px 8px;
transform: translate(500px, 10px);
}
table td{
/* background-color: aqua; */
border: 2px solid black;
padding: 4px 8px;
transform: translate(500px, 10px);
}
.btn{
background-size: 1em;
height: 2em;
width: 3em;
}
body{
margin: 0;
}
.draggable{
padding:1rem;
background-color: aliceblue;
border: 1px solid brown;
cursor: move;
}
.draggable.dragging{
opacity:0.5;
}
button.buttonReset{
color: black;
transform: scale3d(0.2, 0.2, 0.2);
}
.display{
font-family: monospace;
}
button.buttonPlay{
transform: translate(10px);
}
</style>
<link rel="shortcut-icon" href="{{url_for('static', filename='favicon.ico')}}">
</head>
<body>
<div class="container">
<h1>Task Manager</h1>
<br/>
<form action="/my_timers" method="POST">
<input type="text" placeholder="Enter New Task" name = "name" maxlength="10">
<input type="submit" value="+" class="btn btn-secondary" name="hello">
</form>
<br/><br/>
<table>
<tr>
<th>TASK</th>
<th> </th>
<th> </th>
<th>DONE</th>
<th>TIME TAKEN</th>
</tr>
</table>
{% for friend in friends%}
<table>
<tr>
<td>
<div class="container2">
<p class="draggable" draggable="true">
{{ friend.name }} Update
</p>
</div>
</td>
</p>
</td>
<td>
<a href="/delete/{{ friend.id }}">
<button class="btn"> <img src="static/7bdd1bc7db7fd48025d4e39a0e2f0fd8.jpg" alt="button" width="20" height="20" ></button>
</a>
<a href="/description">
<button class="desbtn">+<button>
</a>
</td>
<td>
<div class="stopwatch">
<div class="circle">
<span class="time" id="display">00:00:00</span>
</div>
<div class="controls">
<img id="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg" />
<img id="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg" />
<img id="resetButton" src="/static/download.png" />
</div>
</div>
</td>
</tr>
</table>
<script src="static/new.js"></script>
<!-- <table>
<td>
{{ friend.name }}
</td>
</table> -->
{% endfor%}
</div>
</body>
</html>
AND HERE IS THE JS:
const timer = document.getElementById('circle');
var hr = 0;
var min = 0;
var sec = 0;
var stoptime = true;
function startTimer() {
if (stoptime == true) {
stoptime = false;
timerCycle();
}
}
function stopTimer() {
if (stoptime == false) {
stoptime = true;
}
}
function timerCycle() {
if (stoptime == false) {
sec = parseInt(sec);
min = parseInt(min);
hr = parseInt(hr);
sec = sec + 1;
if (sec == 60) {
min = min + 1;
sec = 0;
}
if (min == 60) {
hr = hr + 1;
min = 0;
sec = 0;
}
if (sec < 10 || sec == 0) {
sec = '0' + sec;
}
if (min < 10 || min == 0) {
min = '0' + min;
}
if (hr < 10 || hr == 0) {
hr = '0' + hr;
}
timer.innerHTML = hr + ':' + min + ':' + sec;
setTimeout("timerCycle()", 1000);
}
}
function resetTimer() {
timer.innerHTML = '00:00:00';
}
The play button, pause button, reset button dont works for any other task that i add.
Please check
So you do not keep track which timer you wanter to play.
I introduce you to classes.
I tried to keep most of your original code intact but I had to made some changes.
First change is as I said, using classes.
this code created a Timer object for each .timer element so it will be easier to keep track of each individual timer.
Second change is adding event listeners so clicking on buttons actually do something
Next is removing sec = parseInt(sec);. That is unnecessary beacause you dont have to keep track of leading 0 in this variable. You can add it just before displaying it for example in printTimer() method.
class Timer
{
timer = null;
hr = 0;
min = 0;
sec = 0;
stopTime = true;
constructor(timer) {
this.timer = timer;
this.setListeners();
}
setListeners = () => {
this.timer.querySelector('.playButton').addEventListener('click', this.startTimer);
this.timer.querySelector('.pauseButton').addEventListener('click', this.stopTimer);
this.timer.querySelector('.resetButton').addEventListener('click', () => {
this.stopTimer();
this.resetTimer();
});
}
startTimer = () => {
if (this.stopTime === true) {
this.stopTime = false;
this.timerCycle();
}
}
stopTimer = () => {
if (this.stopTime === false) {
this.stopTime = true;
}
}
resetTimer = () => {
this.hr = 0;
this.min = 0;
this.sec = 0;
this.printTimer();
}
timerCycle = () => {
if (this.stopTime === false) {
this.sec += 1;
if (this.sec === 60) {
this.min += 1;
this.sec = 0;
}
if (this.min === 60) {
this.hr += 1;
this.min = 0;
}
this.printTimer();
setTimeout(this.timerCycle, 1000);
}
}
printTimer = () => {
const displayHr = this.hr < 10 ? '0' + this.hr : this.hr;
const displayMin = this.min < 10 ? '0' + this.min : this.min;
const displaySec = this.sec < 10 ? '0' + this.sec : this.sec;
this.timer.querySelector('.display').innerHTML = displayHr + ':' + displayMin + ':' + displaySec;
}
}
const timers = document.querySelectorAll('.timer');
timers.forEach(timer => {
new Timer(timer);
});
body {
background-color: khaki;
margin: 0;
}
button.buttonReset {
color: black;
transform: scale3d(0.2, 0.2, 0.2);
}
button.buttonPlay {
transform: translate(10px);
}
.display {
font-family: monospace;
}
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
Related
i would like create a table, where one column would be variables and i want to have "+" and "-" buttons next to it. So when i click button "+" it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table</title>
</head>
<style>
body {
background-color: lightslategray;
}
#PLA {
float: left;
width: 30%;
padding: 10px;
}
th, td {
border: 1px solid;
}
.header {
text-align: center;
font-size: 20px;
}
.celltext {
font-size: 15px;
}
.number {
text-align: center;
}
.vbutton {
background-color: gray;
border: 1px solid black;
border-radius: 6px;
color: white;
text-align: center;
text-decoration: none;
font-size: 10px;
padding: 0px;
margin-right: 4px;
width: 20px;
height: 20px;
float: right;
}
button:hover {
background-color: lightgray;
color: black;
}
.input {
padding: 0px;
width: 48px;
height: 16px;
font-size: 14px;
-webkit-appearance: none;
}
input[type = number] {
-moz-appearance: textfield;
}
input:focus {
border: 0px;
outline: 0px;
}
</style>
<body>
<table id="PLA">
<div>
PLA
<span id="test"></span>
<input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
</div>
<tr class="header">
<td>Barva</td>
<td>Výrobce</td>
<td>Hmotnost (g)</td>
<td>Cena (kg)</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla1">
<span id="wpla1"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla2">
<span id="wpla2"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
</table>
</body>
<script>
// test
test = document.getElementById("test");
// Weight of pla1
wpla1 = document.getElementById("wpla1");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla1weight = localStorage.pla1weight;
localStorage.setItem("pla1weight", pla1weight);
if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
localStorage.pla1weight = 0
pla1weight = 0;
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
else {
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
function changewpla1() {
x = parseInt(wpla1.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla1weight = x - y;
} else {
pla1weight = x + y;
}
wpla1.innerHTML = pla1weight;
wpla1.value = pla1weight;
localStorage.setItem("pla1weight", pla1weight);
nwpla.style.display = "none";
}
// Weight of pla2
wpla2 = document.getElementById("wpla2");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla2weight = localStorage.pla2weight;
localStorage.setItem("pla2weight", pla2weight);
if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
localStorage.pla2weight = 0
pla2weight = 0;
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
else {
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
function changewpla2() {
x = parseInt(wpla2.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla2weight = x - y;
} else {
pla2weight = x + y;
}
wpla2.innerHTML = pla2weight;
wpla2.value = pla2weight;
localStorage.setItem("pla2weight", pla2weight);
nwpla.style.display = "none";
}
function addpla() {
nwpla.value = 0;
p = 0;
nwpla.style.display = "";
}
function subpla() {
nwpla.value = 0
p = 1;
nwpla.style.display = "";
}
function onlyNumberKey(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
</script>
</html>
Any idea?
I would like to have a database as last option. Every value would be saved in local storage.
Thanks.
I have 2 issues with my alarm clock.
1)When the hour is increased or decreased to over 12, I want to switch from AM to PM. The problem is that where I call the today.getHours();, it's inside a different function. My increment button function (to increase/decrease) is outside that function and when moved inside the clock function holding today.getHours(), doesn't work, so I can't say when hours is greater than 12, switch to PM. And it seems redundant to call getHours again. Does anyone have any recommendations on how to fix this in vanilla JS? Is there a better way to do it?
2)When clicked, the minute decrease increment button gives negative values. I know this probably has a simple solution but I think I've been staring at it for too long to see it.
//Select Elements
const alarm_time = document.getElementById('alarmTime');
const set_alarm = document.getElementById('setAlarm');
const alarm_alert = document.getElementById('alarmAlert');
const hr_increase= document.getElementById('hourIncrease');
const hr_decrease = document.getElementById('hourDecrease');
const min_increase= document.getElementById('minuteIncrease');
const min_decrease = document.getElementById('minuteDecrease');
const increment = document.querySelectorAll('.increment');
//Variables
let hr;
let min;
let TOD;
let alarmHr=0;
let alarmMin=0;
let alarmTOD="AM";
let alarmActive=false;
//Alarm Sound
let sound = new Audio("https://res.cloudinary.com/saveallthethings/video/upload/v1565033348/Free%20Music%20Downloads/bensound-hey_vunrwo.mp3");
//Alarm Function
if (alarmHr== hr && parseInt(alarmMin) == min && alarmTOD == TOD){
sound.play();
card.classList.add("blinkingAlarm");
}
//Get Time
function clock(){
//Display Greeting, Time and Date
let today = new Date();
let year = today.getFullYear();
let date = today.getDate();
let hours = today.getHours();
let minutes = today.getMinutes();
//Specify Am or PM, and populate greeting
if (hours >= 17){
timeofDay = "PM";
} else if (hours >= 12 && hours < 17){
timeofDay = "PM";
} else {
timeofDay = " AM";
}
//Convert Hours to 12hr Format
if (hours>12){
hours = hours - 12;
}
else if (hours===0){
hours = 12;
}
//For single digit minutes, add a zero
if (minutes<10){
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (alarm_time.classList.contains("blinkingText")){
alarm_time.innerHTML = (alarmHr + ":" + alarmMin + alarmTOD);
}else{alarm_time.innerHTML = (hours + ":" + minutes + timeofDay);}
}//Closing Brackets for clock fnc
//Set Interval to Update Time
setInterval('clock()', 500);
//Count Clicks on Set Alarm Btn
let clickCounter = 0;
set_alarm.onclick = function() {
clickCounter += 1;
//Second Click sets the alarm, says "Alarm set to"
if((clickCounter % 2) === 0){
alarm_time.classList.remove("blinkingText");
alarmActive = true;
if (alarmHr == 0 && alarmMin == 0){
alarm_alert.innerHTML = "no alarm set";
}else{
alarm_alert.innerHTML = "alarm set for "+ alarmHr +":" + alarmMin + alarmTOD;
}
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
} else {
alarm_time.classList.add("blinkingText");
//Loop Over the Node List for increment
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.add("visibility");
hourDecrease.classList.add("visibility");
minuteIncrease.classList.add("visibility");
minuteDecrease.classList.add("visibility");
document.getElementById("hourIncrease").disabled = false;
document.getElementById("hourDecrease").disabled = false;
document.getElementById("minuteIncrease").disabled = false;
document.getElementById("minuteDecrease").disabled = false;
}
}
};
//Turn off alarm
dismiss.onclick = function() {
if(alarmActive = "true"){
alarmActive ="false"
alarmHr = 0;
alarmMin = 0;
alarmTOD = "AM";
alarm_alert.innerHTML = "no alarm set";
sound.pause();
alarm_time.classList.remove("blinkingText");
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
}
};
hr_increase.onclick = function() {
alarmHr++;
if (alarmHr > 12){
alarmHr= alarmHr - 12;
}
}
hr_decrease.onclick = function() {
alarmHr--;
if (alarmHr <= 0){
alarmHr= alarmHr + 12;
}
console.log(alarmHr);};
min_increase.onclick = function() {
alarmMin++;
if (alarmMin < 10){
alarmMin= "0" + alarmMin;
}
if(alarmMin > 59){
alarmMin= alarmMin-60 ;
}
if(alarmMin == 0){
alarmMin= "00";
}
}
min_decrease.onclick = function() {
alarmMin--;
if (alarmMin < 10){
alarmMin= "0" + minutes;
}
if (alarmMin < 0){
alarmMin= alarmMin % 60;
}
};
#import url('https://fonts.googleapis.com/css?family=Montserrat:900|Open+Sans:800|Source+Sans+Pro:300');
html, body {
height: 100%;
font-family: 'Source Sans Pro', sans-serif;
font-size:15px;
}
.card_container{
height:100vh;
}
.center{
display:flex;
justify-content:center;
align-items:center;
}
.card{
border-radius:15px;
background-color: rgba(254, 253, 253,0.8);
box-shadow: 0px 0px 51px -3px rgba(0,0,0,0.13);
max-width:22rem;
border:solid rgba(254, 253, 253,0.8) 0.1px;
}
.blinkingAlarm{
animation:blinkingAlarm 1.2s ease-in-out infinite;
}
#keyframes blinkingAlarm{
50%{
border:solid white 7px;}
}
.card_inner{
border-radius:15px;
margin:.75rem;
}
.card_currentContainer{
border-radius:15px;
margin-bottom:1rem;
}
.card_alarmContainer {
color:#7E7E7E;
background:#fff;
text-align:center;
}
.card_alarmContainer{
flex-direction:column;
border-radius:15px;
}
.alarmOptions{
display:flex;
color:#7E7E7E;
padding-top:.5rem;
padding-bottom:.5rem;
}
.blinkingText{
animation:blinkingText 1.6s linear infinite;
}
#keyframes blinkingText{
50%{opacity:0.3;}
}
.setBox{
flex-direction:column;
padding-left:.5rem;
padding-right:.5rem;
padding-top:0;
}
.button {
display:block;
border-style:none;
margin: 0px 0px;
padding:0px;
}
.increment{
font-size:1rem;
border:none;
background: rgba(254, 253, 253,0.8);
color:#7E7E7E;
font-family: 'Source Sans Pro', sans-serif;
cursor: pointer;
visibility:hidden;
}
.increment:hover{
cursor:pointer;
color:black;
border-style:none;
}
.visibility{
visibility:visible;
}
.alarmBox{
padding-bottom:.2rem;
}
.alarmTime{
font-size:2rem;
line-height:1rem;
padding-top:.7rem;
}
.alarmAlert{
font-size:.8rem;
text-transform:uppercase;
padding-top:.5rem;
}
.card_buttonsContainer{
width:100%;
margin:1rem 0rem;
justify-content:space-between;
flex-wrap:wrap;
}
.btn{
height:3rem;
width:8rem;
}
#setAlarm{
transition: .2s;
color:#fff;
cursor:pointer;
border-radius:15px;
background: linear-gradient(to left, #ff7e5f , #feb47b);
padding-right:.5rem;
padding-left:.5rem;
font-size:1.5rem;
margin-right:0.3rem;
}
#setAlarm:hover{
border-radius:20px;
opacity: .8;
}
#dismiss{
transition: .2s;
font-size:1.5rem;
color:#fff;
border-radius:15px;
cursor:pointer;
background: linear-gradient(to left, #64B1F2 , #00DBF3);
padding-right:.5rem;
padding-left:.5rem;
margin-left:0.3rem;
}
#dismiss:hover{
border-radius:20px;
opacity: .8;
}
/***Media Queries****/
#media only screen and (max-width:332px) {
.current_greetings{
text-align:center;
}
.card_buttonsContainer{
justify-content:center;
}
.btn{
margin-bottom:.5rem;
}
}
<div class="card_container center">
<div class ="card">
<div class="card_inner">
<div class="card_alarmContainer center">
<div class="alarmOptions ">
<div class="setBox center">
<button class="increment center" id="hourIncrease" disabled>+</button>
<button class="increment center" id="hourDecrease" disabled>−</button>
</div>
<div class="alarmBox">
<div class="alarmTime center" id="alarmTime"></div>
<div class="alarmAlert" id="alarmAlert">no alarm set</div>
</div>
<div class="setBox center">
<button class="increment center" id="minuteIncrease" disabled>+</button>
<button class="increment center" id="minuteDecrease" disabled>−</button>
</div>
</div>
</div>
<div class="card_buttonsContainer center">
<div class ="buttonBox center">
<div class="btn center" id="setAlarm">Set Alarm</div>
</div>
<div class ="buttonBox center">
<div class="btn center" id="dismiss">Dismiss</div>
</div>
</div>
</div>
</div>
</div>
In your code you need to increase and decrease the hour on the minute change. I also suggest pulling the hour increase and hour decrease out into functions (I have sample code of a working solution) so you can use them in the minute increase and decrease functions to increase or decrease the time. I also suggest using a function for the alarm time of day change so you can use it in both your hour increase and hour decrease functions. Your initial value for alarm hour was 0 but there is no 0 hour. I suggest starting with 12 for the alarm hour. I updated all of this in my sample code
The way you can update the TOD is in the hour increase check if the new hour is 12 and then toggle the TOD. In the decrease you check if the new hour is 11 and then toggle the TOD. See my sample working code!
//Select Elements
const alarm_time = document.getElementById('alarmTime');
const set_alarm = document.getElementById('setAlarm');
const alarm_alert = document.getElementById('alarmAlert');
const hr_increase= document.getElementById('hourIncrease');
const hr_decrease = document.getElementById('hourDecrease');
const min_increase= document.getElementById('minuteIncrease');
const min_decrease = document.getElementById('minuteDecrease');
const increment = document.querySelectorAll('.increment');
//Variables
let hr;
let min;
let TOD;
let alarmHr=12;
let alarmMin=0;
let alarmTOD="AM";
let alarmActive=false;
//Alarm Sound
let sound = new Audio("https://res.cloudinary.com/saveallthethings/video/upload/v1565033348/Free%20Music%20Downloads/bensound-hey_vunrwo.mp3");
//Alarm Function
if (alarmHr== hr && parseInt(alarmMin) == min && alarmTOD == TOD){
sound.play();
card.classList.add("blinkingAlarm");
}
function toggleAlarmTOD() {
if(alarmTOD === "AM") {
alarmTOD = "PM"
} else {
alarmTOD = "AM"
}
}
function increaseHr() {
alarmHr++;
if(alarmHr === 12) {
toggleAlarmTOD();
} else if (alarmHr > 12){
alarmHr = alarmHr - 12;
}
}
function decreaseHr() {
alarmHr--;
if(alarmHr <= 0) {
alarmHr = alarmHr + 12;
} else if(alarmHr === 11) {
toggleAlarmTOD();
}
}
//Get Time
function clock(){
//Display Greeting, Time and Date
let today = new Date();
let year = today.getFullYear();
let date = today.getDate();
let hours = today.getHours();
let minutes = today.getMinutes();
//Specify Am or PM, and populate greeting
if(hours >= 12){
timeofDay = "PM";
} else {
timeofDay = " AM";
}
//Convert Hours to 12hr Format
if (hours>12){
hours = hours - 12;
}
else if (hours===0){
hours = 12;
}
//For single digit minutes, add a zero
if (minutes < 10) {
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (alarm_time.classList.contains("blinkingText")){
alarm_time.innerHTML = (alarmHr + ":" + (alarmMin < 10 ? "0" + alarmMin : alarmMin) + alarmTOD);
}else{alarm_time.innerHTML = (hours + ":" + minutes + timeofDay);}
}//Closing Brackets for clock fnc
//Set Interval to Update Time
setInterval('clock()', 500);
//Count Clicks on Set Alarm Btn
let clickCounter = 0;
set_alarm.onclick = function() {
clickCounter++;
//Second Click sets the alarm, says "Alarm set to"
if((clickCounter % 2) === 0){
alarm_time.classList.remove("blinkingText");
alarmActive = true;
if (alarmHr == 0 && alarmMin == 0){
alarm_alert.innerHTML = "no alarm set";
}else{
alarm_alert.innerHTML = "alarm set for " + alarmHr + ":" + (alarmMin < 10 ? "0" + alarmMin : alarmMin) + alarmTOD;
}
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
} else {
alarm_time.classList.add("blinkingText");
//Loop Over the Node List for increment
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.add("visibility");
hourDecrease.classList.add("visibility");
minuteIncrease.classList.add("visibility");
minuteDecrease.classList.add("visibility");
document.getElementById("hourIncrease").disabled = false;
document.getElementById("hourDecrease").disabled = false;
document.getElementById("minuteIncrease").disabled = false;
document.getElementById("minuteDecrease").disabled = false;
}
}
};
//Turn off alarm
dismiss.onclick = function() {
if(alarmActive = "true") {
alarmActive ="false"
alarmHr = 12;
alarmMin = 0;
alarmTOD = "AM";
alarm_alert.innerHTML = "no alarm set";
sound.pause();
alarm_time.classList.remove("blinkingText");
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
}
};
hr_increase.onclick = function() {
increaseHr();
}
hr_decrease.onclick = function() {
decreaseHr();
};
min_increase.onclick = function() {
alarmMin++;
if(alarmMin > 59){
alarmMin = 0;
increaseHr();
}
}
min_decrease.onclick = function() {
alarmMin--;
if (alarmMin < 0){
alarmMin = 59;
decreaseHr();
}
};
#import url('https://fonts.googleapis.com/css?family=Montserrat:900|Open+Sans:800|Source+Sans+Pro:300');
html, body {
height: 100%;
font-family: 'Source Sans Pro', sans-serif;
font-size:15px;
}
.card_container{
height:100vh;
}
.center{
display:flex;
justify-content:center;
align-items:center;
}
.card{
border-radius:15px;
background-color: rgba(254, 253, 253,0.8);
box-shadow: 0px 0px 51px -3px rgba(0,0,0,0.13);
max-width:22rem;
border:solid rgba(254, 253, 253,0.8) 0.1px;
}
.blinkingAlarm{
animation:blinkingAlarm 1.2s ease-in-out infinite;
}
#keyframes blinkingAlarm{
50%{
border:solid white 7px;}
}
.card_inner{
border-radius:15px;
margin:.75rem;
}
.card_currentContainer{
border-radius:15px;
margin-bottom:1rem;
}
.card_alarmContainer {
color:#7E7E7E;
background:#fff;
text-align:center;
}
.card_alarmContainer{
flex-direction:column;
border-radius:15px;
}
.alarmOptions{
display:flex;
color:#7E7E7E;
padding-top:.5rem;
padding-bottom:.5rem;
}
.blinkingText{
animation:blinkingText 1.6s linear infinite;
}
#keyframes blinkingText{
50%{opacity:0.3;}
}
.setBox{
flex-direction:column;
padding-left:.5rem;
padding-right:.5rem;
padding-top:0;
}
.button {
display:block;
border-style:none;
margin: 0px 0px;
padding:0px;
}
.increment{
font-size:1rem;
border:none;
background: rgba(254, 253, 253,0.8);
color:#7E7E7E;
font-family: 'Source Sans Pro', sans-serif;
cursor: pointer;
visibility:hidden;
}
.increment:hover{
cursor:pointer;
color:black;
border-style:none;
}
.visibility{
visibility:visible;
}
.alarmBox{
padding-bottom:.2rem;
}
.alarmTime{
font-size:2rem;
line-height:1rem;
padding-top:.7rem;
}
.alarmAlert{
font-size:.8rem;
text-transform:uppercase;
padding-top:.5rem;
}
.card_buttonsContainer{
width:100%;
margin:1rem 0rem;
justify-content:space-between;
flex-wrap:wrap;
}
.btn{
height:3rem;
width:8rem;
}
#setAlarm{
transition: .2s;
color:#fff;
cursor:pointer;
border-radius:15px;
background: linear-gradient(to left, #ff7e5f , #feb47b);
padding-right:.5rem;
padding-left:.5rem;
font-size:1.5rem;
margin-right:0.3rem;
}
#setAlarm:hover{
border-radius:20px;
opacity: .8;
}
#dismiss{
transition: .2s;
font-size:1.5rem;
color:#fff;
border-radius:15px;
cursor:pointer;
background: linear-gradient(to left, #64B1F2 , #00DBF3);
padding-right:.5rem;
padding-left:.5rem;
margin-left:0.3rem;
}
#dismiss:hover{
border-radius:20px;
opacity: .8;
}
/***Media Queries****/
#media only screen and (max-width:332px) {
.current_greetings{
text-align:center;
}
.card_buttonsContainer{
justify-content:center;
}
.btn{
margin-bottom:.5rem;
}
}
<div class="card_container center">
<div class ="card">
<div class="card_inner">
<div class="card_alarmContainer center">
<div class="alarmOptions ">
<div class="setBox center">
<button class="increment center" id="hourIncrease" disabled>+</button>
<button class="increment center" id="hourDecrease" disabled>−</button>
</div>
<div class="alarmBox">
<div class="alarmTime center" id="alarmTime"></div>
<div class="alarmAlert" id="alarmAlert">no alarm set</div>
</div>
<div class="setBox center">
<button class="increment center" id="minuteIncrease" disabled>+</button>
<button class="increment center" id="minuteDecrease" disabled>−</button>
</div>
</div>
</div>
<div class="card_buttonsContainer center">
<div class ="buttonBox center">
<div class="btn center" id="setAlarm">Set Alarm</div>
</div>
<div class ="buttonBox center">
<div class="btn center" id="dismiss">Dismiss</div>
</div>
</div>
</div>
</div>
</div>
I am writing a simple Coin Flip project to hone my JS skills.
I have a <div id="winMessage"> and I want it to be hidden if I don't click the button for a few seconds. How can I achieve something like this?
I have tried using style.visibility and sleep() to hide/show it between lines but it seems so inefficient and causes lots of problems on other parts.
let heads = 0, tails = 0;
let coinFlip = () => {
let flip = () => {
return Math.floor((Math.random() * 2) + 1);
}
let result = flip();
if (result === 1){
heads++;
document.getElementById("winMessage").innerHTML = "Heads!"
}
else if (result === 2) {
tails++;
document.getElementById("winMessage").innerHTML = "Tails!"
}
document.getElementById("heads").innerText = heads;
document.getElementById("tails").innerHTML = tails;
}
<head>
<title>Coin Flipper</title>
<link rel="stylesheet" href="style.css" class="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
crossorigin="anonymous">
</head>
<body class="bg-dark text-warning" style="margin: auto;">
<header>
<h1>Coin Flip</h1>
</header>
<form>
<div>
<button type="button" class="btn btn-warning" onclick="coinFlip()" style="width: 100%;">Flip It!</button>
</div>
</form>
<div id="winMessage" style="float: center; text-align: center; font-size: 100px; padding-bottom: 10px;"></div>
<div style="float: center; text-align: center;">
<div>Heads Count: <div id="heads" style=></div></div>
<div>Tails Count: <div id="tails"></div></div>
</div>
</body>
```
Use setTimeout() and clearTimeout():
const hide = setTimeout() in main scope, with your delay as a second argument
clearTimeout(hide) on the button click
element.style.display = "none" to hide the element
optionally, as you use Bootstrap, I guess you can use jQuery .hide() instead
let heads = 0, tails = 0;
let coinFlip = () => {
clearTimeout(hide);
let flip = () => {
return Math.floor((Math.random() * 2) + 1);
}
let result = flip();
if (result === 1){
heads++;
document.getElementById("winMessage").innerHTML = "Heads!"
}
else if (result === 2) {
tails++;
document.getElementById("winMessage").innerHTML = "Tails!"
}
document.getElementById("heads").innerText = heads;
document.getElementById("tails").innerHTML = tails;
}
const hide = setTimeout(() => {
document.getElementById('winMessage').style.display = 'none'
}, 3000)
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
crossorigin="anonymous">
<header>
<h1>Coin Flip</h1>
</header>
<form>
<div>
<button type="button" class="btn btn-warning" onclick="coinFlip()" style="width: 100%;">Flip It!</button>
</div>
</form>
<div id="winMessage" style="float: center; text-align: center; font-size: 100px; padding-bottom: 10px;">Hides after 3000ms</div>
<div style="float: center; text-align: center;">
<div>Heads Count: <div id="heads" style=></div></div>
<div>Tails Count: <div id="tails"></div></div>
</div>
For the simple way use css. With css animation.
#keyframes showHide {
0% { opacity: 0; }
10% { opacity: 0.2 }
20% { opacity: 0.35 }
50% { opacity: 1 }
60% { opacity: 0.75 }
100 % { opacity: 0; }
}
#winMessage {
height: 100px;
opacity: 0;
width: 100px;
background: red;
animation-name: showHide;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-delay: 1s;
}
<div id="winMessage" style="float: center; text-align: center; font-size: 100px; padding-bottom: 10px;"></div>
You should start a timer at the start of your program. Every time the button is pressed then the timer should be erased and a new timer should start. Here is an example using setTimeout and clearTimeout.
var time = 5000;
var timeoutID = setTimeout(hideElement, time);
document.querySelector("#button").addEventListener("click", delay);
function delay() {
clearTimeout(timeoutID);
timeoutID = setTimeout(hideElement, time);
}
function hideElement() {
document.querySelector("#hide").style.display = "none";
}
<div id="hide">Hiding</div>
<button id="button">Delay</button>
This is how it would look like on your question:
let heads = 0,
tails = 0;
const time = 5000;
let timeoutID = setTimeout(hideMessage, time);
let coinFlip = () => {
let flip = () => {
return Math.floor((Math.random() * 2) + 1);
}
let result = flip();
if (result === 1) {
heads++;
document.getElementById("winMessage").innerHTML = "Heads!"
} else if (result === 2) {
tails++;
document.getElementById("winMessage").innerHTML = "Tails!"
}
document.getElementById("heads").innerText = heads;
document.getElementById("tails").innerHTML = tails;
clearTimeout(timeoutID);
timeoutID = setTimeout(hideMessage, time);
// If you do not want it to reappear, remove this line
document.querySelector("#winMessage").style.display = null;
};
function hideMessage() {
document.querySelector("#winMessage").style.display = "none";
}
<head>
<title>Coin Flipper</title>
<link rel="stylesheet" href="style.css" class="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body class="bg-dark text-warning" style="margin: auto;">
<header>
<h1>Coin Flip</h1>
</header>
<form>
<div>
<button type="button" class="btn btn-warning" onclick="coinFlip()" style="width: 100%;">Flip It!</button>
</div>
</form>
<div id="winMessage" style="float: center; text-align: center; font-size: 100px; padding-bottom: 10px;"></div>
<div style="float: center; text-align: center;">
<div>Heads Count:
<div id="heads" style=></div>
</div>
<div>Tails Count:
<div id="tails"></div>
</div>
</div>
</body>
Something like this :
setTimeout(() => {
document.getElementById("winMessage").style.display = 'none';
}, 3000); // 3 seconds
<div id="winMessage">winMessage</div>
I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});
This question already has answers here:
How to move an element into another element
(16 answers)
Closed 7 years ago.
I am new at JavaScript. I am trying to make Snakes and Ladders game with native JavaScript code as much as possible. My problem is that I can not move players from their initial position according to the random number generated when pressing on dice image. Can anyone help me on how to move players?
var gameBoard = {
createBoard: function(dimension, mount, intialPosition) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table, intialPosition);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = 'lastCell';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = 'firstCell';
intialPosition();
return gameBoard;
}
};
window.onload = (function(e) {
gameBoard.createBoard(10, "#grid", intialPosition);
});
var face1 = new Image()
face1.src = "d1.gif"
var face2 = new Image()
face2.src = "d2.gif"
var face3 = new Image()
face3.src = "d3.gif"
var face4 = new Image()
face4.src = "d4.gif"
var face5 = new Image()
face5.src = "d5.gif"
var face6 = new Image()
face6.src = "d6.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
function intialPosition() {
$("#firstCell").append($("#player1"));
$("#firstCell").append($("#player2"));
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#lastCell {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="oie_eRDOY2iqd5oQ.gif" />
</div>
<div id="bigSnake">
<img src="oie_485727sRN4KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="humanPiece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="computerPiece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="reset">New Game</button>
</div>
<div>
<button type="button" name="reset">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
<!--<h2 id="status" style="clear:left;"></h2>-->
</div>
</div>
</div>
<script src="JavaScript1.js"></script>
</body>
</html>
I fell miserable about not being able to finish the game. I really need help. Thanks in advance.
Well, first of all this question has been already asked and answered on SO and table cells are just the same as usual elements :)
Since you're using jQuery anyway, you can use .detach()
var element = $('td:eq(0) span').detach();
$('td:eq(1)').append(element);
Here's a jsfiddle.
Or, as proposed in this answer, you can use a native js solution.