javascript while loop not performing functions inside - javascript

I'm a student and new so I'm sorry if my formatting is off. I am having a problem with my while loop not executing the main functions inside the loop. I'm not sure what I'm doing wrong. I am making a tic tac toe game with a mario theme and a fair amount is working but my while loop runs through itself until it hits 'i = 9' and it seems to increase my marioCount to 9 as well but my goal was to have it alternate between classes when I click on a new box and that doesn't work. I always get bowser. Please help if possible and go easy on me, i'm a beginner. Thanks in advance.
$(document).ready(function() {
var $quare = $('.square');
var $brd = $('.board');
var $tart = $('#start');
var $bmario = $('#mario');
var $bbowser = $('#bowser');
var $cchar = $('#cchar');
var clickedSquare = 0;
var bowserCount = 0;
marioCount = 0;
$cchar.hide();
$bmario.hide();
$bbowser.hide();
$brd.hide();
$tart.on('click', function revealButton() {
$bmario.show();
$bbowser.show();
$cchar.show();
})
$bmario.on('click', function() {
$brd.show();
$bbowser.hide();
var i = 0
while (i < 9) {
if(marioCount % 2 === 0) {
$quare.on('click', function() {
$(this).addClass('smario clicked');
})
} else {
$quare.on('click', function() {
$(this).addClass('sbowser clicked');
})
}
marioCount++
i++
}
})
})
This is the HTML for my game
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mario Tic Tac Toe</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div id="allBody">
<div id="header">
<div id="title">Tic Tac Toe</div>
</div>
<div id="startDiv">
<button class="button" id="start">Start Game</button>
</div>
<div id="cchar">Pick Your Character</div>
<div id="choose">
<button class="button" id="mario"></button>
<button class="button" id="bowser"></button>
</div>
<div class="board">
<table class="tabl">
<!-- <tbody id="tbody"> -->
<tr id="row1">
<td class="square " id="square1"></td>
<td class="square vmiddle" id="square2"></td>
<td class="square" id="square3"></td>
</tr>
<tr id="row2">
<td class="square hmiddle" id="square4"></td>
<td class="square vmiddle hmiddle" id="square5"></td>
<td class="square hmiddle" id="square6"></td>
</tr>
<tr id="row3">
<td class="square" id="square7"></td>
<td class="square vmiddle" id="square8"></td>
<td class="square" id="square9"></td>
</tr>
<!-- </tbody> -->
</table>
<!-- Game Here -->
</div>
<div id="info">...</div>
</div>
<script src="js/jquery-2.2.0.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Here's the CSS for the game
html {
background: url(http://i1.kym-cdn.com/photos/images/original/000/939/881/cf4.png) no-repeat center center fixed;
background-size: cover;
}
#title {
text-align: center;
color: yellow;
font-size: 50px;
}
#startDiv {
text-align: center;
margin: 0 auto;
}
#choose {
text-align: center;
margin: 0 auto;
}
#mario {
background: url("../images/Mario_super_cool.jpg");
background-size: cover;
height: 35px;
width: 35px;
}
#bowser {
background: url("../images/Bowser.jpg");
background-size: cover;
height: 35px;
width: 35px;
}
#cchar {
color: yellow;
text-align: center;
font-size: 30px;
}
#start {
text-align: center;
margin: 0 auto;
border-radius: 15px;
color: yellow;
font-size: 35px;
}
.smario {
background: url("../images/Mario_super_cool.jpg");
background-size: cover;
height: 125px;
width: 125px;
}
.sbowser {
background: url("../images/Bowser.jpg");
background-size: cover;
height: 125px;
width: 125px;
}
.board {
}
table {
margin: auto;
background: rgba(171, 39, 7, 0.5);
}
.square {
float: left;
font-family: 'Londrina Shadow', cursive;
font-size: 50px;
height: 125px;
margin: 0px;
text-align: center;
vertical-align: middle;
width: 125px;
}
.vmiddle {
border-left: 5px solid yellow;
border-right: 5px solid yellow;
opacity: 1.4;
}
.hmiddle {
border-top: 5px solid yellow;
border-bottom: 5px solid yellow;
}

You don't need a loop here. Have a look at this code.
$(".square").on("click", function () {
if (!$(this).hasClass("clicked")) { // do something if this square hasn't been clicked
if (marioCount % 2 === 0) {
$(this).addClass("smario clicked");
} else {
$(this).addClass('sbowser clicked');
}
marioCount++;
}
});

Replace "< 9" with "< 10", since you are essentially saying "do this while i is 8 or less, but NOT 9", instead of what you want, "do this while i is 9 or less, but NOT 10".

Related

How to set relative position of tooltip in CSS/JS?

I know there are lots of similar questions but I can't get it to work and hope you can help me.
I have a nested list of items. Mostly simple hrefs but some are links which should call a copy-to-clipboard function and display a success message in as span afterwards.
The message should be displayed above the link and centered. On a desktop with high resolution there is no problem. On mobile,unfortunately showing the span uses space and moves the hrefs + the position is anywhere but above and in the middle.
Using data-tooltip class templates didn't work for me because they normally use "hover". In my case the span should only be displayed after clicking the link and shouldn't mess up the other elements.
function CopyToClipboard(id) {
// do copy stuff here
// [...]
// showing tooltip
var span_element = document.getElementById(id).parentElement.querySelector('span');
if(span_element != null) {
span_element.style.display = "inline";
setTimeout( function() {
span_element.style.display = "none";
}, 2000);
}
}
body {
margin-left: 0px;
}
ul {
padding-left: 20px;
}
div.container {
margin: 10px;
width: 98%;
word-break: break-all;
}
.custom-tooltip {
padding: 4px;
background-color: grey;
color: #fff;
position: relative;
bottom: 2em;
right: 5em;
display: none;
}
<html lang="de" class=" heujtnrdy idc0_345">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.90">
<link rel="stylesheet" href="index_tmp.css">
<script type="text/javascript" src="index_tmp.js"></script>
</head>
<body>
<div class="container">
<ul>
<li>
<span>Layer 1</span>
<ul>
<li>
<span>Layer 2</span>
<ul>
<li>
<span>Layer 3</span>
<ul>
<li>
<div>
<table>
<tr>
<td><a id="uGzkLTVmLY" onclick="CopyToClipboard('uGzkLTVmLY');return false;" href="#">Short text to copy</a><span class="custom-tooltip">Copied!</span></td>
</tr>
</table>
</div>
</li>
<li>
<div>
<table>
<tr>
<td><a id="VF5DVP6tVv" onclick="CopyToClipboard('VF5DVP6tVv');return false;" href="#">Looooooooooooooooooong text to copy</a><span class="custom-tooltip">Copied!</span></td>
</tr>
</table>
</div>
</li>
<li>
<div>
<table>
<tr>
<td><a id="VF5DVP6tVv" onclick="CopyToClipboard('VF5DVP6tVv');return false;" href="#">Even loooooooooooooooooooooooooooooooooooooooooooooooooooooonger text to copy</a><span class="custom-tooltip">Copied!</span></td>
</tr>
</table>
</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
-- Update 05.02.2023 --
Here my modified CSS, based on granite's alternative solution. This looks like this:
.modal {
display: none;
position: fixed;
padding-top: 50%;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
text-align: center;
justify-content: center;
}
.modal-content {
background-color: grey;
border: 0.5px solid grey;
border-radius: 3px;
color: #fff;
text-align: center;
margin: 0 auto;
padding: 2px;
padding-left: 10px;
padding-right: 10px;
font-size: 1.0em;
font-family: monospace;
font-weight: 700;
bottom: 1em !important;
position: fixed;
}
As a secondary option (via modal):
Html: 2 lines code.
CSS: 7 extra lines code.
JS: 10 extra lines code.
Just need to get the JS CopyToClipboard to link up.
<button id="MBtn" id="VF5DVP6tVv" onclick="CopyToClipboard('VF5DVP6tVv');return false;">long text to copy</button>
<div id="Modal" class="modal"><div class="modal-content">Copied!</div></div>
.modal {
display: none;
position: fixed;
padding-top: 25%;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #eff;
text-align:center;
margin: 0 auto;
padding: 3px;
width:4em;
}
var modal = document.getElementById("Modal");
var btn = document.getElementById("MBtn");
btn.onclick = function() {
modal.style.display = "block";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}

ion-datetime dynamic value change doesn't work for certain weeks

This is a very strange problem to describe, but I'll try to do my best.
First of all, I'm working with vanilla JavaScript, I don't want to use Angular, React or anything like that because I don't know anything about them (although I wouldn't be against using jQuery if it was necessary).
What I'm trying to achieve
I'm trying to make a week selector using an ion-datetime element. I use this because it is the best option I could find to make a week selector while showing the whole calendar. If there is a less problematic way to do it, I'm open to hear it.
The way I do this is by listening to the ionChange event, detecting the clicked day, calculating the 7 days that belong to the same week and replacing calendar.value with the new array (see code below).
The problem
The thing is that when I click on certain weeks (it always happens in the same ones), an error pops up: TypeError: Cannot read properties of undefined (reading 'year'), but the process is always the same.
I add here a video of the problem in action: https://streamable.com/8toc8g
Code
#import url('https://fonts.googleapis.com/css2?family=Lilita+One&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght#700&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Indie+Flower&display=swap');
:root {
--bg-rosa: #f3e1e3;
--top1-rosa: #fbb6ad;
--top2-rosa: #b4dadf;
--top1-rosa-aux: #facec8;
--top2-rosa-aux: #d5e7e8;
--bg-turquesa: #d5e7e8;
--top1-turquesa: #6ccac8;
--top2-turquesa: #efb049;
--top1-turquesa-aux: #8fd9d8;
--top2-turquesa-aux: #f0cb90;
--bg-amarillo: #fffdeb;
--top1-amarillo: #ffe373;
--top2-amarillo: #ffabab;
--top1-amarillo-aux: #fff0b3;
--top2-amarillo-aux: #ffc7c7;
--bg-morado: #ece4ff;
--top1-morado: #a4a4eb;
--top2-morado: #a1dae6;
--top1-morado-aux: #c2c2f2;
--top2-morado-aux: #c7ebf2;
--bg: var(--bg-morado);
--top1: var(--top1-morado);
--top1-aux: var(--top1-morado-aux);
--top2: var(--top2-morado);
--top2-aux: var(--top2-morado-aux);
--top-text: #444c53;
}
body {
position: relative;
background: var(--bg);
padding: 0;
margin: 0;
}
.week {
display: grid;
grid-template-columns: repeat(7, minmax(10em, 25em));
width: 100%;
height: 100%;
padding: 1em;
}
.day {
position: relative;
flex-grow: 1;
height: 100%;
}
.day::after {
content: "";
display: block;
width: 100%;
height: 100%;
background: var(--bg);
opacity: 0;
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
.day:hover::after {
opacity: 0.2;
}
.top {
display: flex;
align-items:center;
justify-content:center;
padding: 0.35em;
font-family: 'Lilita One', cursive;
font-size: min(calc(1em + 1vw), calc(1em + 2vh));
color: var(--top-text);
text-align: center;
vertical-align: baseline;
border-radius: calc(1em + 1vh) calc(1em + 1vh) 0 0;
}
.content {
border-radius: 0 0 calc(1em + 1vh) calc(1em + 1vh);
}
.info {
/* height: 49vh; */
height: calc(49vh - 0.4vw);
font-family: 'Indie Flower', cursive;
font-weight: 500;
font-size: 1.2rem;
padding: 0.5rem 0.5rem 0 1rem;
overflow-y: scroll;
background-color: #ffffff;
background-size: 1.5rem 1.5rem;
background-image: repeating-linear-gradient(0deg, #d7d7d780, #d7d7d780 1px, #ffffff 1px, #ffffff);
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track-piece:end {
background: transparent;
margin-bottom: 1.5vh;
}
::-webkit-scrollbar-thumb {
border-radius: 8px;
background: #c2c9d2;
}
.frame {
padding: 0 0.25em 0.25em 0.25em;
height: calc(100% - min(calc(1em + 1vw), calc(1em + 2vh)) - 2em);
}
.frame-square {
background-color: var(--top1);
}
.frame-dotted {
background-color: var(--top2);
}
.square {
background-position: center;
background-color: var(--top1);
background-image: linear-gradient(var(--top1-aux) 2px, transparent 2px), linear-gradient(90deg, var(--top1-aux) 2px, transparent 2px);
background-size: 1em 0.9em, 1em 0.9em;
}
.dotted {
background-position: center;
background-color: var(--top2);
background: radial-gradient(circle, transparent 20%, var(--top2) 20%, var(--top2) 80%, transparent 80%, transparent), radial-gradient(circle, transparent 20%, var(--top2) 20%, var(--top2) 80%, transparent 80%, transparent) 17.5px 17.5px, linear-gradient(var(--top2-aux) 1.4px, transparent 1.4px) 0 -0.7px, linear-gradient(90deg, var(--top2-aux) 1.4px, var(--top2-aux) 1.4px) -0.7px 0;
background-size: 35px 35px, 35px 35px, 17.5px 17.5px, 17.5px 17.5px;
}
#calendario {
width: 30vw;
height: 40vh;
margin: 0;
margin-left: 1em;
margin-bottom: 1em;
border-style: solid;
border-color: var(--top1);
border-radius: 1em;
}
.ion-color-same {
--ion-color-base: var(--top1);
--ion-color-contrast: white;
}
ion-datetime {
--background: var(--bg);
border-radius: 16px;
margin-right: 5em;
}
table {
height: 100%;
width: 100%;
}
#inf {
padding: 0;
margin: 0;
height: 15rem;
}
#frase {
margin: 3rem;
font-family: 'Dancing Script', 'Lilita One', cursive;
color: var(--top-text);
}
#frase-container {
width: 100%;
height: 100%;
text-align: center;
}
#fondo-frase {
display: flex;
height: calc(100% - 1em);
width: calc(100% - 2em);
max-height: calc(100% - 1em);
max-width: calc(100% - 2em);
margin: 1em;
margin-top: 0;
align-items:center;
justify-content:center;
}
ion-datetime::part(datetime-year){
background: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<script type="module" src="https://cdn.jsdelivr.net/npm/#ionic/core/dist/ionic/ionic.esm.js"></script>
<script nomodule src="https://cdn.jsdelivr.net/npm/#ionic/core/dist/ionic/ionic.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#ionic/core/css/ionic.bundle.css" />
<link rel="stylesheet" href="style.css">
<script>
function valueChanged() {
const calendario = document.getElementById('calendario');
if (calendario.value.length != 7) {
const last = calendario.value[calendario.value.length - 1];
let date = new Date(last);
date = getMonday(date);
selectFromMonday(date);
}
}
function getMonday(date) {
switch (date.getDay()) {
case 2:
date.setDate(date.getDate() - 1);
break;
case 3:
date.setDate(date.getDate() - 2);
break;
case 4:
date.setDate(date.getDate() - 3);
break;
case 5:
date.setDate(date.getDate() - 4);
break;
case 6:
date.setDate(date.getDate() - 5);
break;
case 0:
date.setDate(date.getDate() - 6);
break;
}
return date;
}
async function selectFromMonday(date) {
let calendario = document.getElementById('calendario');
let diaIds = ['lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado', 'domingo'];
let value = [];
for (let i = 0; i < 7; i++) {
const dia = document.getElementById(diaIds[i]);
value.push(date.getFullYear() + "-" + parseInt(date.getMonth()+1) + "-" + date.getDate());
dia.getElementsByClassName('fecha')[0].value = value[value.length - 1];
dia.getElementsByClassName('content info')[0].innerHTML = "";
date.setDate(date.getDate() + 1);
}
calendario.value = value;
}
</script>
</head>
<body>
<table id="tabla">
<tr id="sup"><td>
<div class="week">
<div class="day" id="lunes">
<input type="hidden" class="fecha">
<div class="top square">LUNES</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
<div class="day" id="martes">
<input type="hidden" class="fecha">
<div class="top dotted">MARTES</div>
<div class="content frame frame-dotted">
<div class="content info"></div>
</div>
</div>
<div class="day" id="miercoles">
<input type="hidden" class="fecha">
<div class="top square">MIÉRCOLES</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
<div class="day" id="jueves">
<input type="hidden" class="fecha">
<div class="top dotted">JUEVES</div>
<div class="content frame frame-dotted">
<div class="content info"></div>
</div>
</div>
<div class="day" id="viernes">
<input type="hidden" class="fecha">
<div class="top square">VIERNES</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
<div class="day" id="sabado">
<input type="hidden" class="fecha">
<div class="top dotted">SÁBADO</div>
<div class="content frame frame-dotted">
<div class="content info"></div>
</div>
</div>
<div class="day" id="domingo">
<input type="hidden" class="fecha">
<div class="top square">DOMINGO</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
</div>
</td></tr>
<tr><td id="inf">
<table><tr><td>
<ion-datetime id="calendario"
presentation="date"
locale="es-ES"
first-day-of-week="1"
min="1970-01-01T00:00:00"
max="2200-12-31T23:59:59"
size="cover"
color="same"
multiple="true">
</ion-datetime>
</td><td id="frase-container">
<div id="fondo-frase">
<h1 id="frase"></h1>
</div>
</td></tr></table>
</td>
</tr>
</table>
<script>
let today = new Date();
//today.setTime( today.getTime() - today.getTimezoneOffset() * 60 * 1000 );
let monday = getMonday(today);
selectFromMonday(monday);
let calen = document.getElementById('calendario');
calen.addEventListener('ionChange', function () {
valueChanged()
});
</script>
</body>
</html>
Okay, I finally found the problem. I initially used the Date.toISOString() method and splitted the result to get just the date, but since it gave me a date outside my timezone I had to do it manually.
So the thing is that when I used my own method, I did not take into account that for 1 digit days (or months) it adds a zero before so that it's 2 digits. For example, for October 3 2022 I got 2022-10-3 with my method and 2022-10-03 with the other one, and that was what caused the problems.

Loop through Rounds while calling for New user Selection after each round Javascript

I am working on a Rock Paper Scissors game, and I am stuck on a for concepts. I want the user to select the amount of rounds they want through a textbox. Each time the user clicks on a specific image (rock, paper, or scissors) the computer will randomly compile and this will select and image for the computer. Both user and computer chosen images will display in the center of the page in the red and blue squares. I want this to run in a loop until all rounds are complete and then decide an ultimate winner. I am getting lost on how I will make my Loop call for the function where I am having the user select an image, and do this until cpu or user wins. All I am looking for is a bit of guidance as to why I can't figure out how to call for the users selection and then chose a user selection, and repeat this process to completion.
function startGame() {
document.getElementById("gameInfo").style.display = "contents";
}
function clearGame() {
document.getElementById("gameInfo").style.display = "none";
document.getElementById("cpu").src = "";
document.getElementById("user").src = "";
document.getElementById("winner").innerHTML = "";
document.getElementById("userDisplay").innerHTML = "";
document.getElementById("userName").value = "";
}
function displayName() {
var txtName = document.getElementById("userName").value;
document.getElementById("userDisplay").innerHTML = txtName;
}
/*function roundNumber(input) {
var total = document.getElementById("roundChoice").value;
//compSelection(total.value);
console.log(total);
}*/
function userPick(input) {
document.getElementById("user").src = input.src;
roundNumber(input.id);
console.log(input.id);
}
function roundNumber(uInput) {
var total;
var element = document.getElementById("roundChoice").value;
if (element != null) {
total = element.value;
document.getElementById("roundChoice").value = "Let's Begin";
} else {
document.getElementById("roundChoice").value = "Enter Rounds!!!";
}
for (var i = 0; i <= total; i++) {
var compSelect = Math.floor(Math.random() * 3 + 1);
var winner = document.getElementById("winner");
if (compSelect === 1) {
document.getElementById("cpu").src = "images/rock.jpg";
if (uInput === "rock_1") {
winner.innerHTML = "you tied!"
i--;
} else if (uInput === "paper_1") {
winner.innerHTML = "User Wins Round" + i + "!"
} else {
winner.innerHTML = "Computer Wins Round" + i + "!"
}
} else if (compSelect === 2) {
document.getElementById("cpu").src = "images/paper.jpg";
if (uInput === "paper_1") {
winner.innerHTML = "You tied!"
i--;
} else if (uInput === "scissors_1") {
winner.innerHTML("User Wins Round" + i + "!")
} else {
winner.innerHTML = "Computer Wins Round" + i + "!"
}
} else {
document.getElementById("cpu").src = "images/scissors.jpg";
if (uInput === "scissors_1") {
winner.innerHTML = "You tied!"
i--;
} else if (uInput === "rock_1") {
winner.innerHTML = "User Wins Round" + i + "!"
} else {
winner.innerHTML = "computer WIns"
}
}
}
}
body {
font: 80% arial, helvetica, sans-serif;
background: black;
margin: 0;
}
#container {
position: relative;
width: 1100px;
border: solid orange;
border-width: 0 3px;
margin: auto;
overflow: hidden;
height: 78em;
}
#header {
padding: 1em;
position: relative;
overflow: hidden;
}
#title {
color: white;
text-align: center;
font: 280% courier;
text-decoration: none;
text-shadow: 1px 1px 8px orange;
}
p.instruct {
background: grey;
color: white;
text-align: center;
font-size: 120%;
position: relative;
border: solid orange;
border-width: 1px;
padding: .5em 0 .5em 0;
}
#startButton {
float: left;
margin: 0 0 2em 2em;
}
#button {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#clearButton {
margin: 0 0 0 12em;
}
#newButton {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#modifiedGame {
float: right;
margin: 0 2em 2em 0;
}
#newGameBtn {
background: black;
border: dotted red;
color: red;
padding: 4px;
}
#nameInput {
text-align: center;
margin: 3em 0 1em 0;
}
#userName {
text-align: center;
background: black;
border: dotted orange;
padding: 4px;
}
#submitName {
margin: 0 0 5em 39em;
}
#rounds {
clear: both;
text-align: center;
margin: 0;
}
#roundChoice {
text-align: center;
padding: 4px;
border: dotted orange;
background: black;
}
#enterRounds {
margin: 1em 0 2em 39.5em;
}
p.winner {
background: grey;
color: white;
/*clear: both;*/
}
::placeholder {
color: orange;
}
input,
select,
textarea {
color: orange;
}
#images,
p {
clear: both;
color: white;
}
#images {
float: left;
}
#images2 {
float: right;
}
#cpuNameTag {
text-align: center;
color: white;
margin: 0 0 0 45em;
}
#cpuNameTag2 {
color: white;
float: left;
}
#paper_1 {
width: 80px;
height: 80px;
}
#paper_2 {
width: 80px;
height: 80px;
}
#rock_1 {
width: 80px;
height: 80px;
}
#rock_2 {
width: 80px;
height: 80px;
}
#scissors_1 {
width: 80px;
height: 80px;
}
#scissors_2 {
width: 80px;
height: 80px;
}
#rock {
float: left;
}
#paper {
float: left;
}
#scissors {
float: left;
}
#rock2 {
float: right;
}
#scissors2 {
float: right;
}
#paper2 {
float: right;
}
#user_displayed_choice {
background-color: red;
width: 150px;
height: 150px;
float: right;
}
#cpu_displayed_choice {
clear: both;
background-color: blue;
width: 150px;
height: 150px;
float: right;
}
#displayed_choices {
margin: 0 31em 0 0;
}
#user {
width: 100px;
height: 100px;
}
#cpu {
width: 100px;
height: 100px;
}
#gameInfo {
display: none;
}
h4 {
color: orange;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CSS intro" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<title>Rock Paper Scissors</title>
<link href="rps.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="rps.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1 id="title"><b>Welcome </b><br><b>to</b> <br><b>Rock Paper Scissors!</b></h1>
</div>
<!--Instructions for game-->
<p class="instruct">Ready to attempt a game of Rock, Paper, Scissors? Select the start button, and then choose the amount of rounds you want to play. Ties in each round will not count towards total rounds. If a tie is present at the end of all the rounds, one final overtime
round will decide the winner. If you dare, try our harder version by beating the computer to unlock.</p>
<!--Buttons for Start, Clear, and Harder Game-->
<div id="modifiedGame">
<input type="button" id="newGameBtn" onclick="newGame" value="Want to try a harder game?">
</div>
<div id="startButton">
<input type="button" id="button" onclick="startGame()" value="Start Game">
</div>
<section id="gameInfo">
<div id="clearButton">
<input type="button" id="newButton" onclick="clearGame()" value="Clear Game">
</div>
<!--^^^-->
<!--Name Input, Round Input-->
<div id="nameInput">
<input type="text" id="userName" placeholder="What is your name?" autofocus required>
</div>
<div id="submitName">
<input type="button" id="nameButton" value="Secure Name" onclick="displayName(this)">
</div>
<div id="rounds">
<input type="text" id="roundChoice" placeholder="Enter # of Rounds" autofocus required>
</div>
<div id="enterRounds">
<input type="button" id="roundButton" value="Set Rounds" onclick="roundNumber(this)">
</div>
<div id="cpuNameTag2">
<h4 id="userDisplay" value=""></h4>
</div>
<div id="cpuNameTag">
<h4>CPU Chooses:</h4>
</div>
<!--Clickable Images for User to Choose. Some Displayed by CPU name to show what CPU Chose after User-->
<div id="images">
<div id="rock">
<img src="images/rock.jpg" alt="rock" id="rock_1" onclick="userPick(this)">
</div>
<div id="paper">
<img src="images/paper.jpg" alt="paper" id="paper_1" onclick="userPick(this)">
</div>
<div id="scissors">
<img src="images/scissors.jpg" alt="scissors" id="scissors_1" onclick="userPick(this)">
</div>
</div>
<div id="images2">
<div id="scissors2">
<img src="images/scissors.jpg" alt="scissors" id="scissors_2">
</div>
<div id="paper2">
<img src="images/paper.jpg" alt="paper" id="paper_2">
</div>
<div id="rock2">
<img src="images/rock.jpg" alt="rock" id="rock_2">
</div>
</div>
<div id="displayed_choices">
<div id="cpu_displayed_choice">
<img id="cpu" src="">
</div>
<div id="user_displayed_choice">
<img id="user" src="">
</div>
</div>
<h1 id="winner"></h1>
</section>
</div>
</body>
</html>
Here you have a working example without the for loop, using 3 global variables (currentRound, totalRounds and wins).
var currentRound = -1;
var totalRounds = -1;
var wins = -1;
function startGame() {
document.getElementById("gameInfo").style.display = "contents";
}
function clearGame() {
document.getElementById("gameInfo").style.display = "none";
document.getElementById("cpu").src = "";
document.getElementById("user").src = "";
document.getElementById("winner").innerHTML = "";
document.getElementById("userDisplay").innerHTML = "";
document.getElementById("userName").value = "";
}
function displayName() {
var txtName = document.getElementById("userName").value;
document.getElementById("userDisplay").innerHTML = txtName;
}
function setRounds() {
var value = document.getElementById("roundChoice").value;
if (value) {
totalRounds = parseInt(value);
currentRound = 0;
wins = 0;
document.getElementById("winner").innerHTML = "Let's Begin";
} else {
document.getElementById("roundChoice").value = "Enter Rounds!!!";
totalRounds = -1;
}
}
function userPick(input) {
if (totalRounds < 0) {
alert("Enter Rounds!!!");
return;
}
if (currentRound >= totalRounds) {
alert("Rounds Finished! Enter Rounds again!!!");
return;
}
//console.log(currentRound + "," + totalRounds)
document.getElementById("user").src = input.src;
currentRound++;
roundNumber(input.id);
}
function roundNumber(uInput) {
var compSelect = Math.floor(Math.random() * 3 + 1);
var winner = document.getElementById("winner");
var i = currentRound + 1;
if (compSelect === 1) {
document.getElementById("cpu").src = "https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg";
if (uInput === "rock_1") {
winner.innerHTML = "you tied!"
currentRound--;
} else if (uInput === "paper_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "Computer Wins Round " + i + "!"
}
} else if (compSelect === 2) {
document.getElementById("cpu").src = "https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png";
if (uInput === "paper_1") {
winner.innerHTML = "You tied!"
currentRound--;
} else if (uInput === "scissors_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "Computer Wins Round " + i + "!"
}
} else {
document.getElementById("cpu").src = "https://image.flaticon.com/icons/png/128/164/164986.png";
if (uInput === "scissors_1") {
winner.innerHTML = "You tied!"
currentRound--;
} else if (uInput === "rock_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "computer WIn " + i + "!"
}
}
if (currentRound == totalRounds) {
alert(totalRounds + " Finished:\n"
+ "- wins: " + wins + "\n"
+ "- looses: " + (totalRounds - wins))
}
}
body {
font: 80% arial, helvetica, sans-serif;
background: black;
margin: 0;
}
input[type=button],
#images img {
cursor: pointer;
}
#container {
position: relative;
width: 1100px;
border: solid orange;
border-width: 0 3px;
margin: auto;
overflow: hidden;
height: 78em;
}
#header {
padding: 1em;
position: relative;
overflow: hidden;
}
#title {
color: white;
text-align: center;
font: 280% courier;
text-decoration: none;
text-shadow: 1px 1px 8px orange;
}
p.instruct {
background: grey;
color: white;
text-align: center;
font-size: 120%;
position: relative;
border: solid orange;
border-width: 1px;
padding: .5em 0 .5em 0;
}
#startButton {
float: left;
margin: 0 0 2em 2em;
}
#button {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#clearButton {
margin: 0 0 0 12em;
}
#newButton {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#modifiedGame {
float: right;
margin: 0 2em 2em 0;
}
#newGameBtn {
background: black;
border: dotted red;
color: red;
padding: 4px;
}
#nameInput {
text-align: center;
margin: 3em 0 1em 0;
}
#userName {
text-align: center;
background: black;
border: dotted orange;
padding: 4px;
}
#submitName {
margin: 0 0 5em 39em;
}
#rounds {
clear: both;
text-align: center;
margin: 0;
}
#roundChoice {
text-align: center;
padding: 4px;
border: dotted orange;
background: black;
}
#enterRounds {
margin: 1em 0 2em 39.5em;
}
p.winner {
background: grey;
color: white;
/*clear: both;*/
}
::placeholder {
color: orange;
}
input,
select,
textarea {
color: orange;
}
#images,
p {
clear: both;
color: white;
float: left;
}
#images2 {
float: right;
}
#cpuNameTag {
text-align: center;
color: white;
margin: 0 0 0 45em;
}
#cpuNameTag2 {
color: white;
float: left;
}
#paper_1 {
width: 80px;
height: 80px;
}
#paper_2 {
width: 80px;
height: 80px;
}
#rock_1 {
width: 80px;
height: 80px;
}
#rock_2 {
width: 80px;
height: 80px;
}
#scissors_1 {
width: 80px;
height: 80px;
}
#scissors_2 {
width: 80px;
height: 80px;
}
#rock {
float: left;
}
#paper {
float: left;
}
#scissors {
float: left;
}
#rock2 {
float: right;
}
#scissors2 {
float: right;
}
#paper2 {
float: right;
}
#user_displayed_choice {
background-color: red;
width: 150px;
height: 150px;
float: right;
}
#cpu_displayed_choice {
clear: both;
background-color: blue;
width: 150px;
height: 150px;
float: right;
}
#displayed_choices {
margin: 0 31em 0 0;
}
#user {
width: 100px;
height: 100px;
}
#cpu {
width: 100px;
height: 100px;
}
#gameInfo {
display: none;
}
h4 {
color: orange;
}
#winner {
text-align: center;
color: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CSS intro" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<title>Rock Paper Scissors</title>
<link href="rps.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="rps.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1 id="title"><b>Welcome </b><br><b>to</b> <br><b>Rock Paper Scissors!</b></h1>
</div>
<!--Instructions for game-->
<p class="instruct">Ready to attempt a game of Rock, Paper, Scissors? Select the start button, and then choose the amount of rounds you want to play. Ties in each round will not count towards total rounds. If a tie is present at the end of all the rounds, one final overtime
round will decide the winner. If you dare, try our harder version by beating the computer to unlock.</p>
<!--Buttons for Start, Clear, and Harder Game-->
<div id="modifiedGame">
<input type="button" id="newGameBtn" onclick="newGame" value="Want to try a harder game?">
</div>
<div id="startButton">
<input type="button" id="button" onclick="startGame()" value="Start Game">
</div>
<section id="gameInfo">
<div id="clearButton">
<input type="button" id="newButton" onclick="clearGame()" value="Clear Game">
</div>
<!--^^^-->
<!--Name Input, Round Input-->
<div id="nameInput">
<input type="text" id="userName" placeholder="What is your name?" autofocus required>
</div>
<div id="submitName">
<input type="button" id="nameButton" value="Secure Name" onclick="displayName(this)">
</div>
<div id="rounds">
<input type="text" id="roundChoice" placeholder="Enter # of Rounds" autofocus required>
</div>
<div id="enterRounds">
<input type="button" id="roundButton" value="Set Rounds" onclick="setRounds()">
</div>
<div id="cpuNameTag2">
<h4 id="userDisplay" value=""></h4>
</div>
<div id="cpuNameTag">
<h4>CPU Chooses:</h4>
</div>
<!--Clickable Images for User to Choose. Some Displayed by CPU name to show what CPU Chose after User-->
<div id="images">
<div id="rock">
<img src="https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg" alt="rock" id="rock_1" onclick="userPick(this)">
</div>
<div id="paper">
<img src="https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png" alt="paper" id="paper_1" onclick="userPick(this)">
</div>
<div id="scissors">
<img src="https://image.flaticon.com/icons/png/128/164/164986.png" alt="scissors" id="scissors_1" onclick="userPick(this)">
</div>
</div>
<div id="images2">
<div id="scissors2">
<img src="https://image.flaticon.com/icons/png/128/164/164986.png" alt="scissors" id="scissors_2">
</div>
<div id="paper2">
<img src="https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png" alt="paper" id="paper_2">
</div>
<div id="rock2">
<img src="https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg" alt="rock" id="rock_2">
</div>
</div>
<div id="displayed_choices">
<div id="cpu_displayed_choice">
<img id="cpu" src="">
</div>
<div id="user_displayed_choice">
<img id="user" src="">
</div>
</div>
<h1 id="winner"></h1>
</section>
</div>
</body>
</html>

I am trying to insert a chunk of html code dynamically with Javascript reading smaple json, but unable to do so

Went through a few questions on stackoverflow but could not solve the error.
The intention is to modify and add html to the main document reading a JSON structure.
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Update 1:-
Typo was corrected, marked in code.
Defer was introduced at script load in head section, this makes sure the entire document is loaded before the script starts execution.
Here I am trying to read a JSON, and then looping across its content to add to my main html document.
var json={
"fruit":[
{
"fruitname":"Apple",
"location":"data/png/apple.png",
"quantity":"25",
"price":"2"
},
{
"fruitname":"Mango",
"location":"data/png/mango.png",
"quantity":"35",
"price":"3"
}
]
};
//var cards = document.getElementsByClassName("content"); -- corrected typo
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
var cardelement=document.createElement('div');
cardelement.className = 'card';
// alert(cardelement);
cards.appendChild(cardelement);
var object = document.createElement('div');
object.className = 'object';
// alert(object);
cardelement.appendChild(object);
var image = document.createElement('img');
image.setAttribute("src", fruits[i].location);
object.appendChild(image);
var objectback = document.createElement('div');
objectback.className = 'object-back';
cardelement.appendChild(objectback);
var backfruit = document.createElement('div');
backfruit.className = 'back-fruit';
backfruit.innerHTML = fruits[i].fruitname;
objectback.appendChild(backfruit);
var backprice = document.createElement('div');
backprice.className = 'back-price';
backprice.innerHTML = fruits[i].price + "$ per unit";
objectback.appendChild(backprice);
var backquantity = document.createElement('div');
backquantity.className = 'back-quantity';
backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
objectback.appendChild(backquantity);
}
*
{
margin: 0 0;
border: none;
text-align:center
}
#header
{
background-color: #F44336;
font-family: 'Bungee Shade', cursive;
font-size: 30px;
height: 20%
}
#footer
{
font-family: 'Roboto', sans-serif;
position: fixed;
height: 80%;
width: 100%
}
#content
{
width: 75%;
height: 100%;
border-right: thick solid #F44336;
float: left;
text-align: left;
overflow: scroll
}
#cart
{
background-color:#3F51B5;
width: 25%;
border-bottom: thick dashed #F44336;
float: right
}
.card
{
display:inline-block;
width: 100px;
height: 100px;
margin: 40px;
padding: 20px;
box-shadow: -1px 9px 20px 4px #000000;
border: 5px solid #F44336;
border-radius: 26px 26px 26px 26px;
transition: all .2s ease-in-out
}
.object .object-back
{
display:block;
position:static
}
.object-back
{
display: none
}
.object img
{
height: 100px;
width: 100px
}
.back-fruit
{
font-size: 20px;
padding-bottom: 5px;
margin-bottom: 10px;
border-bottom: thin solid
}
.back-price
{
font-size: 12px;
padding-bottom: 5px
}
.back-quantity
{
font-size: 10px;
padding-bottom: 10px
}
.back-pluscart
{
font-size: 15px;
background-color: #F44336;
width: auto
}
.back-pluscart img
{
height: 30px;
width: 30px
}
.card:hover
{
box-shadow: -1px 9px 46px 11px #000000
}
.card:hover .object
{
display: none
}
.card:hover .object-back
{
display:inline-block;
opacity: 1
}
<!DOCTYPE html>
<html>
<head>
<title> The Shopkeeper </title>
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel = "stylesheet" type = "text/css" href = "style/style.css" />
<script type="text/javascript" src="logic/core.js" defer></script>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="base">
<div id="header">
<h1> Fruitkart </h1>
</div>
<div id="footer">
<div id="content">
<!--
<div class="card">
<div class="object">
<img src="data/png/apple.png" />
</div>
<div class="object-back">
<div class="back-fruit">Apple</div>
<div class="back-price">2$ per unit</div>
<div class="back-quantity">In Stock 25 pieces </div>
<div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
</div>
</div>
-->
</div>
<div id="cart">
django
is a big boy
</div>
</div>
</div>
</body>
</html>
Why was content undefined
You try to get content by ClassName
var cards = document.getElementsByClassName("content")[0];
But find content in your html:
<div id="content">
Notice that the ID is content. Either change it to class="content" or change the previous code to document.getElementByID("content");
Two issues:
There is no element with class content. On the other hand there is an element with that id. So you probably want to do:
document.getElementById("content");
The script runs too soon -- the elements are not loaded yet when it runs. Either put the script just before the closing </body> tag, or put the code inside an event handler, like
window.addEventListener('DOMContentLoaded', function() {
// your code
});
You are trying to access an element with class name content var cards =document.getElementsByClassName("content")[0]; & there is no class named content
You can modify your code like this ,
var cards = document.getElementById("content");
var json={
"fruit":[
{
"fruitname":"Apple",
"location":"data/png/apple.png",
"quantity":"25",
"price":"2"
},
{
"fruitname":"Mango",
"location":"data/png/mango.png",
"quantity":"35",
"price":"3"
}
]
};
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
var cardelement=document.createElement('div');
cardelement.className = 'card';
// alert(cardelement);
cards.appendChild(cardelement);
var object = document.createElement('div');
object.className = 'object';
// alert(object);
cardelement.appendChild(object);
var image = document.createElement('img');
image.setAttribute("src", fruits[i].location);
object.appendChild(image);
var objectback = document.createElement('div');
objectback.className = 'object-back';
cardelement.appendChild(objectback);
var backfruit = document.createElement('div');
backfruit.className = 'back-fruit';
backfruit.innerHTML = fruits[i].fruitname;
objectback.appendChild(backfruit);
var backprice = document.createElement('div');
backprice.className = 'back-price';
backprice.innerHTML = fruits[i].price + "$ per unit";
objectback.appendChild(backprice);
var backquantity = document.createElement('div');
backquantity.className = 'back-quantity';
backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
objectback.appendChild(backquantity);
}
*
{
margin: 0 0;
border: none;
text-align:center
}
#header
{
background-color: #F44336;
font-family: 'Bungee Shade', cursive;
font-size: 30px;
height: 20%
}
#footer
{
font-family: 'Roboto', sans-serif;
position: fixed;
height: 80%;
width: 100%
}
#content
{
width: 75%;
height: 100%;
border-right: thick solid #F44336;
float: left;
text-align: left;
overflow: scroll
}
#cart
{
background-color:#3F51B5;
width: 25%;
border-bottom: thick dashed #F44336;
float: right
}
.card
{
display:inline-block;
width: 100px;
height: 100px;
margin: 40px;
padding: 20px;
box-shadow: -1px 9px 20px 4px #000000;
border: 5px solid #F44336;
border-radius: 26px 26px 26px 26px;
transition: all .2s ease-in-out
}
.object .object-back
{
display:block;
position:static
}
.object-back
{
display: none
}
.object img
{
height: 100px;
width: 100px
}
.back-fruit
{
font-size: 20px;
padding-bottom: 5px;
margin-bottom: 10px;
border-bottom: thin solid
}
.back-price
{
font-size: 12px;
padding-bottom: 5px
}
.back-quantity
{
font-size: 10px;
padding-bottom: 10px
}
.back-pluscart
{
font-size: 15px;
background-color: #F44336;
width: auto
}
.back-pluscart img
{
height: 30px;
width: 30px
}
.card:hover
{
box-shadow: -1px 9px 46px 11px #000000
}
.card:hover .object
{
display: none
}
.card:hover .object-back
{
display:inline-block;
opacity: 1
}
<!DOCTYPE html>
<html>
<head>
<title> The Shopkeeper </title>
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel = "stylesheet" type = "text/css" href = "style/style.css" />
<script type="text/javascript" src="logic/core.js" ></script>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="base">
<div id="header">
<h1> Fruitkart </h1>
</div>
<div id="footer">
<div id="content">
<!--
<div class="card">
<div class="object">
<img src="data/png/apple.png" />
</div>
<div class="object-back">
<div class="back-fruit">Apple</div>
<div class="back-price">2$ per unit</div>
<div class="back-quantity">In Stock 25 pieces </div>
<div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
</div>
</div>
-->
</div>
<div id="cart">
django
is a big boy
</div>
</div>
</div>
</body>
</html>

Highlight Table Row using onMouseOver and onMouseOut with external JavaScript file

I need to highlight a table row (exluding the table head), but I can not use CSS hover. I must use JavaScript onMouseOver and onMouseOut events. The JavaScript must be contained in an external file.
I am already using the external JavaScript file to print the date in the footer. For some reason onMouseOver and onMouseOut are not calling "trackTableHighlight" or "highlightTableRow". What am I doing wrong?
Here is test.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<script src="test.js"></script>
</head>
<body>
<div id="wrapper">
<header>
<h1>Test</h1>
</header>
<nav>
<ul>
<li>Home</li>
</ul>
</nav>
<div class="main">
<div class="middle-content">
<br>
<table class="stripe_table">
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tbody onMouseOver="trackTableHighlight(event, '#8888FF')" onMouseOut="highlightTableRow(0)">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<footer>
<p>
Today is:
<script>printDate();</script>
</p>
</footer>
</div>
</div>
</body>
</html>
Here is test.js:
function printDate()
{
document.write(Date());
}
function trackTableHighlight(mEvent, highlightColor)
{
if (!mEvent)
mEvent=window.event;
// Internet Explorer
if (mEvent.srcElement)
{
highlightTableRow( mEvent.srcElement, highlightColor);
}
// Netscape and Firefox
else if (mEvent.target)
{
highlightTableRow( mEvent.target, highlightColor);
}
}
function highlightTableRow(myElement, highlightColor)
{
var i=0;
// Restore color of the previously highlighted row
for (i; i<savedStateCount; i++)
{
restoreBackgroundStyle(savedStates[i]);
}
savedStateCount=0;
while (myElement &&
((myElement.tagName && myElement.tagName!="TR") || !myElement.tagName))
{
myElement=myElement.parentNode;
}
if (!myElement || (myElement && myElement.id && myElement.id=="header") )
return;
if (myElement)
{
var tableRow=myElement;
if (tableRow)
{
savedStates[savedStateCount]=saveBackgroundStyle(tableRow);
savedStateCount++;
}
var tableCell=findNode(myElement, "TD");
var i=0;
while (tableCell)
{
if (tableCell.tagName=="TD")
{
if (!tableCell.style)
{
tableCell.style={};
}
else
{
savedStates[savedStateCount]=saveBackgroundStyle(tableCell);
savedStateCount++;
}
tableCell.style["backgroundColor"]=highlightColor;
tableCell.style.cursor='default';
i++;
}
tableCell=tableCell.nextSibling;
}
}
}
Here is test.css:
html {
height: 100%;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: linear-gradient(to bottom, #FFFFFF, #4F6D93) no-repeat;
color: #666666;
height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
}
header {
background-color: #000033;
color: #FFFFFF;
height: 60px;
text-align: center;
padding-top: 15px;
}
nav {
font-weight: bold;
padding: 20px;
float: left;
width: 160px;
}
nav ul {
list-style-type:none;
margin: 0px;
padding-left: 0px;
font-size: 1.2em;
}
h1 {
font-family: "Times New Roman", Georgia, Serif;
margin-top: 0px;
}
footer {
font-size: 75%;
font-style: italic;
text-align: center;
font-family: "Times New Roman", Georgia, Serif;
padding: 20px;
}
#wrapper {
margin: auto;
width: 80%;
background-color: #90C7E3;
min-width: 960px;
max-width: 2048px;
box-shadow: 3px 3px 3px #333333;
position: relative;
}
.middle-content {
padding-left: 1%;
padding-right: 1%;
padding-bottom: 1%;
}
.main {
background-color: #FFFFFF;
border: 3px solid white;
margin-left: 190px;
padding-left: 30px;
margin-bottom: 5%;
}
table {
margin-left:auto;
margin-right:auto;
border-collapse: collapse;
width: 80%;
text-align: center;
}
table, th, td {
border: 2px solid #90C7E3;
}
th, td {
padding: 15px;
}
th {
background: #000033;
color: white;
}
td:nth-child(2) {
text-align: left;
}
Here is a little test in jsfiddle: https://jsfiddle.net/a2Lxqxqe/2/ (I'm not sure about browser compatibility issues but you can see it working just fine in Chrome):
document.addEventListener("DOMContentLoaded", function(event) {
var tr = document.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
tr[i].addEventListener("mouseover", function() {
this.style.backgroundColor = "#8888FF";
});
tr[i].addEventListener("mouseout", function() {
this.style.backgroundColor = "transparent";
});
}
});
function printDate() {
document.write(Date());
}
Instead of addEventListener you can use attachEvent() if you need support for: IE8 and below and/or Opera 6 and below. Here is a little reference to this: http://www.w3schools.com/jsref/met_document_addeventlistener.asp
I wrapped the code in document.addEventListener("DOMContentLoaded", function(event){ ... }) so the code executes after the DOM is loaded, if not you'll get an error when hovering.

Categories

Resources