JavaScript problem adding a class to HTML [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Good day
I am starting to practice with JavaScript and recently I mounted a simple digital clock using the local time of my pc, I have proposed to add something else to it, to show me the current day in which we are, I want to achieve this with a single tag <p> where it contains the days: Mon - Tue - Wed - Thu - Fri - Sat - Sun, The idea is to apply a different style to the current day using a <span> tag, I do not know if it is the correct way to do it or if there is a more efficient way that consumes less resources and I would like you to help me with this to improve my code .
My current problem boils down to somehow that I am misusing the Element.classList.add (" class "); and I can't update the class of my element.
I attach my code:
"use strict";
const hour = document.getElementById("hour");
const date = document.getElementById("date");
const days = document.getElementById("day");
let daysString = '<span id="mon"> Mon </span> - <span id="tue"> Tue </span> - <span id="wed"> Wed </span> - ' +
'<span id="thu">Thu </span> - <span id="fri"> Fri </span> - <span id="sat"> Sat </span> - <span id="sun"> Sun </span>';
const nameMonths = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
days.innerHTML = daysString;
const getTime = ()=>{
const local = new Date();
let day = local.getDate(),
month = local.getMonth(),
year = local.getFullYear();
let getTime = local.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: true });
let time = getTime.slice(0, -2);
let moment = getTime.slice(-2);
hour.innerHTML = `${time} <span class="ampm">${moment[0]}.${moment[1]}.</span>`;
date.innerHTML = `${day} / ${nameMonths[month]} / ${year}`;
// ------------------------------------------------------------------------------------------------------------
let d = local.getDay();
let finalDays = daysString;
days.innerHTML = finalDays;
let currentDay;
switch(d){
case 0:
currentDay = document.getElementById("sun");
currentDay.classList.add("active-day");
break;
case 1:
currentDay = document.getElementById("mon");
currentDay.classList.add("active-day");
break;
case 2:
currentDay = document.getElementById("tue");
currentDay.classList.add("active-day");
break;
case 3:
currentDay = document.getElementById("wed");
currentDay.classList.add("active-day");
break;
case 4:
currentDay = document.getElementById("thu");
currentDay.classList.add("active-day");
break;
case 5:
currentDay = document.getElementById("fri");
currentDay.classList.add("active-day");
break;
case 6:
currentDay = document.getElementById("sat");
currentDay.classList.add("active-day");
break;
default:
finalDays = daysString;
}
days.innerHTML = finalDays;
}
getTime();
setInterval(getTime,1000);
* {
margin: 0;
padding: 0;
}
body{
background: url(background2.jpg) no-repeat center center fixed;
background-size: cover;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: 'lato';
}
.container-clock{
text-align: center;
color: #fff;
}
.container-clock h1{
font-size: 12rem;
font-weight: 400;
text-shadow: 0 0 20px #409CFA;
}
.dates{
font-size: 2.5rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-shadow: 0 0 10px #409CFA;
}
.days{
font-size: 1.5rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
color: rgb(155, 155, 155);
text-shadow: 0 0 8px #409CFA;
}
.active-day{
color: #fff;
text-shadow: 0 0 10px #409CFA;
font-size: 2rem;
}
.ampm{
font-size: 5rem;
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Digital clock</title>
</head>
<body ondragstart="return false" onselectstart="return false" oncontextmenu="return false">
<div class="container-clock">
<h1 id="hour">00:00:00</h1>
<p id="date" class="dates">date</p>
<br><br>
<p id="day" class="days">day-day-day-day-day-day-day</p>
</div>
<script src="clock.js"></script>
</body>
</html>
I can not get the desired effect since I can not add the desired class to the elements, I would appreciate whoever tells me that I am doing wrong.
In the same way, I would appreciate any advice and / or ideas on how to improve this code, for example, I understand that it would be better to use if / else thanswitch ()since it consumes less resources.
I have also realized that I am not deleting the active day class when the day ends at 23:59, in the same way at the moment there is no class to replace or delete until I solve my problem.
Thank you very much in advance to anyone who can help me!

there is a problem in line 31:
fecha.innerHTML = `${day} / ${nameMonths[month]} / ${year}`;
you didn't defined the varible fecha
the main problem you showed here happening because you copy the 'innerHTML' of day, then change things inside day, and paste back the innerHTML you copied.
the solution is just removing the lines:
let finalDays = daysString;
days.innerHTML = finalDays;
and the line at the end:
days.innerHTML = finalDays;
a thing I noticed is that you are changing the html of days at the beginning of the java script, you don't need to do that if you can just write this in the html
i wrote a simplification for the switch case you wrote:
let d = local.getDay();
let currentDay = days.children[(d + 6) % 7];
let lastDay = days.children[(d + 5) % 7];
currentDay.className = "active-day";
lastDay.className = "inactive-day";
(i added 6 instead of removing 1 because (0 - 1) % 7 is -1 and not 6)
instead of
const getTime = ()=>{
you can just write
function getTime() {
(its more standard)
the final code:
"use strict";
const hour = document.getElementById("hour");
const date = document.getElementById("date");
const days = document.getElementById("day");
const nameMonths = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
function getTime() {
const local = new Date();
let day = local.getDate(),
month = local.getMonth(),
year = local.getFullYear();
let getTime = local.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: true });
let time = getTime.slice(0, -2);
let moment = getTime.slice(-2);
hour.innerHTML = `${time} <span class="ampm">${moment[0]}.${moment[1]}.</span>`;
//fecha.innerHTML = `${day} / ${nameMonths[month]} / ${year}`;
// ------------------------------------------------------------------------------------------------------------
let d = local.getDay();
let currentDay = days.children[(d + 6) % 7];
let lastDay = days.children[(d + 5) % 7];
currentDay.className = "active-day";
lastDay.className = "inactive-day";
}
getTime();
setInterval(getTime,1000);
* {
margin: 0;
padding: 0;
}
body{
background: url(background2.jpg) no-repeat center center fixed;
background-size: cover;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: 'lato';
}
.container-clock{
text-align: center;
color: #fff;
}
.container-clock h1{
font-size: 12rem;
font-weight: 400;
text-shadow: 0 0 20px #409CFA;
}
.active-day {
color: aqua;
}
.inactive-day {
color: red;
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Digital clock</title>
</head>
<body ondragstart="return false" onselectstart="return false" oncontextmenu="return false">
<div class="container-clock">
<h1 id="hour">00:00:00</h1>
<p id="date" class="dates">date</p>
<br><br>
<p id="day" class="days">
<span class="inactive-day">Mon</span>-
<span class="inactive-day">Tue</span>-
<span class="inactive-day">Wed</span>-
<span class="inactive-day">Thu</span>-
<span class="inactive-day">Fri</span>-
<span class="inactive-day">Sat</span>-
<span class="inactive-day">Sun</span>
</p>
</div>
<script src="clock.js"></script>
</body>
</html>
btw, you don't need to worry about consuming less resources because javascript is not for making thing that need lot of resources
(sorry if my english is bad, its not my native language)

Related

How to add timer until tomorrow in HTML

I am beginner in HTML and I am trying to put a timer in my HTML university project daily word game that shows time left until the next day and word. I found a W3Schools tutorial for a timer but it does not work for me because it is until constant date.
My code looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="images/tabIcon.ico">
<title>Daily WordGame</title>
<style>
h1 {
font-family: Tahoma, sans-serif;
text-align: center;
}
p {
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to your daily source of educational fun</h1>
<hr>
<p style="font-size: large;">Everyday you have a chance of guessing a different word.
</p>
Go to about
<p>this is a second text</p>
<ul>
<li>Boats</li>
<li>Cars</li>
<ul>
<li>Buggati</li>
<table>
<tr>
<td>Price</td>
<td>Top speed</td>
<td>0-100</td>
<td>Horse Power</td>
</tr>
<tr>
<td>3.300.000$</td>
<td>420km/h</td>
<td>2.2s</td>
<td>1480</td>
</tr>
</table>
<img src="images/car.jpg" style="width: 500px;height:300px;">
</ul>
<li>Trucks</li>
</ul>
</body>
<html>
Add a span or any text element with an id of timer
<span id="timer">Time until next word: </span>
And add JavaScript code to get the countdown
<script>
var now = new Date();
// If you want another time, set it here with javascrip Date API
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var tomorrow = new Date().setDate(now.getDate() + 1);
var timer = document.getElementById("timer");
// Update the count down every 1 second
setInterval(() => {
// Fill in with the time until tomorrow
var time = new Date(tomorrow - now);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
// Format the time to add a leading 0 if less than 10
function fillZero(n) {
if (n < 10) {
return "0" + n;
} else return n.toString();
}
timer.innerText = "Time until next word: " + "0d " + fillZero(hours) + "h " + fillZero(minutes) + "m " + fillZero(seconds) + "s";
}, 1000);
</script>
So the modified code with your HTML is
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="images/tabIcon.ico">
<title>Daily WordGame</title>
<style>
h1 {
font-family: Tahoma, sans-serif;
text-align: center;
}
p {
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to your daily source of educational fun</h1>
<hr>
<p style="font-size: large;">Everyday you have a chance of guessing a different word.
</p>
Go to about
<p>this is a second text</p>
<span id="timer">Time until next word: </span>
<ul>
<li>Boats</li>
<li>Cars</li>
<ul>
<li>Buggati</li>
<table>
<tr>
<td>Price</td>
<td>Top speed</td>
<td>0-100</td>
<td>Horse Power</td>
</tr>
<tr>
<td>3.300.000$</td>
<td>420km/h</td>
<td>2.2s</td>
<td>1480</td>
</tr>
</table>
<img src="images/car.jpg" style="width: 500px;height:300px;">
</ul>
<li>Trucks</li>
</ul>
<script>
var now = new Date();
// If you want another time, set it here with javascrip Date API
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var tomorrow = new Date().setDate(now.getDate() + 1);
var timer = document.getElementById("timer");
// Update the count down every 1 second
setInterval(() => {
// Fill in with the time until tomorrow
var time = new Date(tomorrow - now);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
// Format the time to add a leading 0 if less than 10
function fillZero(n) {
if (n < 10) {
return "0" + n;
} else return n.toString();
}
timer.innerText = "Time until next word: " + "0d " + fillZero(hours) + "h " + fillZero(minutes) + "m " + fillZero(seconds) + "s";
}, 1000);
</script>
</body>
<html>

Time for populating a UI dynamically increases linearly, with each try?

Requirement:
User will enter "Number of Containers" and "Number of Controls"
Random input elements (numeric, checkbox, etc) will be created and equally distributed among the containers.
When user clicks on "Create" again, the input elements shown in the UI will be deleted and new set of random input elements will be populated again.
Issue:
Every time I create new set of input elements, the time taken for creating increases linearly up to a point then decreases little and increases again
I use the below code to empty the div that accommodates the containers and create input elements
Emptying the overall div
node.innerHTML = ""
Creating a numeric control with label
function createNumber(display) {
let controlWrap = document.createElement("div");
let label = document.createElement("label")
let control = document.createElement("input")
control.type = "number";
label.append("Numeric Input");
label.append(control);
controlWrap.append(label);
controlWrap.style.display = display;
controlWrap.classList.add("ctrl");
return controlWrap;
}
Find the entire code below,
//Constands
const CTRL_DISPLAY_TYPE = "block"
//Selection
const numOfContainers = document.querySelector("#numOfContainers");
const numOfControls = document.querySelector("#numOfControls");
const createContainersBtn = document.querySelector("#create");
const containerWrapper = document.querySelector(".containerWrapper");
const controlHeading = document.querySelectorAll(".ctrlHeading");
//Event Listeners
createContainersBtn.addEventListener("click",createContainers);
controlHeading.forEach(element => element.addEventListener("click"),expandControl);
//Support-functions
function createControl(newControlContainer){
let newControlWrapper = document.createElement("div")
newControlWrapper.classList.add("ctrlWrapper");
let newControl = createNumber(CTRL_DISPLAY_TYPE);
newControlWrapper.appendChild(newControl);
newControlContainer.appendChild(newControlWrapper);
}
function createNumber(display){
let controlWrap = document.createElement("div");
let label = document.createElement("label")
let control = document.createElement("input")
control.type = "number";
label.append("Numeric Input");
label.append(control);
controlWrap.append(label);
controlWrap.style.display = display;
controlWrap.classList.add("ctrl");
return controlWrap;
}
function calculateControlPerContainer(numOfContainers,numOfControls,maxLimit){
let controlsPerContainer = []
let pendingControls = numOfControls%numOfContainers
let controlPerContainerNum = Math.floor(numOfControls/numOfContainers)
for (let i=0;i<numOfContainers;i++){
if (pendingControls>0){
newControlsPerContainer=controlPerContainerNum+1;
controlsPerContainer.push(newControlsPerContainer);
--pendingControls;
}
else{
controlsPerContainer.push(controlPerContainerNum);
}
}
return controlsPerContainer
}
function expandControl(event){
const control = event.currentTarget.nextElementSibling;
if (control.style.display === "none"){
control.style.display = "block";
}
else {
control.style.display = "none"
}
}
//utility-functions
function removeChild(node){
while(node.firstChild){
node.removeChild(node.firstChild);
}
}
function clearNodeData(node){
node.innerHTML = ""
}
//main-Functions
function createContainers(event){
console.time("Deleting controls");
const controlsPerContainer = calculateControlPerContainer(parseInt(numOfContainers.value),parseInt(numOfControls.value));
clearNodeData(containerWrapper);
//removeChild(containerWrapper);
console.timeEnd("Deleting controls");
console.time("populating controls");
controlsPerContainer.forEach(num=>{
let newControlContainer = document.createElement("div")
newControlContainer.classList.add("ctrlContainer");
for(let j=0;j<num;j++){
createControl(newControlContainer);
}
containerWrapper.appendChild(newControlContainer);
})
console.timeEnd("populating controls");
}
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
border: 0;
height:100%
}
.containerWrapper{
display:flex;
flex-direction: row;
height: 90%;
}
.ctrlContainer{
/* flex-grow:1; */
flex-shrink: 0;
border-style: solid;
border-width: 0.5px;
margin:0 2px;
flex-basis: calc(25% - 4px);
align-items: stretch;
display:flex;
flex-direction: column;
overflow: auto;
}
.ctrlWrapper{
border-style: solid;
border-width: .5px;
margin:2px
}
.ctrlHeading{
display:block;
width: 100%;
text-align: left;
border: 0;
}
.ctrl{
display:none;
}
<!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>Dynamic Controls</title>
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<label for="numOfContainers">Number of Containers</label>
<input type="number" id="numOfContainers" name="numOfContainers" min="1" max="500" value="100">
<label for="numOfControls">Number of Controls</label>
<input type="number" id="numOfControls" name="numOfControls" min="1" max="1500" value="1500"><br>
<button id="create">Create</button>
<div class="containerWrapper">
<!-- <div class="ctrlContainer">
<div class="ctrlWrapper">
<button class="ctrlHeading">Checkbox</button>
<input class="ctrl" type="checkbox">
</div>
<div class="ctrlWrapper">
<button class="ctrlHeading">Checkbox</button>
<input class="ctrl" type="checkbox">
</div>
</div>
<div class="ctrlContainer">2</div>
<div class="ctrlContainer">3</div> -->
</div>
<script type="module" src="scripts/MainBackup.js"></script>
</body>
</html>
I tried analyzing using chrome developer tools and could see "append" function is taking more total time. Please let me know if I am doing something wrong in deleting or adding controls and how to avoid this time build up with every run.
More Information after some more exploration:
I am seeing this behavior only in chrome. In firefox and edge, there is no time buildup.
Firefox:
This occurs only in my system. Others are not able to replicate.
The time build-up occurs in portion of code in which I append inputs to the label to assign it to the input without using id. If I directly append the input to container, the time buildup doesn't happen

Can't get the numeric value from HTML using parseInt or Number in my js function

So I'm trying to complete this simple html page for a friend's project, the goal is to get 2 user entries, minutes and seconds, that will be compared to the data already in the table and if the minutes and seconds entered are greater than one of the time in the table, it will be replaced by the entry.
I've never worked with js except to make some simple prompt or alert so I don't know what I'm supposed to do.
Here is the html, js and css :
function timeEntry() {
var min1 = Number(document.getElementById('firstTimeMin'));
var sec1 = Number(document.getElementById('firstTimeSec'));
var min2 = Number(document.getElementById('secondTimeMin'));
var sec2 = Number(document.getElementById('secondTimeSec'));
var min3 = Number(document.getElementById('thirdTimeMin'));
var sec3 = Number(document.getElementById('thirdTimeSec'));
var entryMin = Number(prompt('What is the time in minutes ?'));
var newTimeMin = entryMin;
var entrySec = Number(prompt('What is the time in seconds'));
var newTimeSec = entrySec;
for (var i = 0; i < 3; i++) {
if (entryMin > min1 && entrySec > sec1) {
document.getElementById('firstTimeMin').innerHTML = newTimeMin;
document.getElementById('firstTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min2 && entrySec > sec2) {
document.getElementById('secondTimeMin').innerHTML = newTimeMin;
document.getElementById('secondTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min3 && entrySec > sec3) {
document.getElementById('thirdTimeMin').innerHTML = newTimeMin;
document.getElementById('thirdTimeSec').innerHTML = newTimeSec;
break;
}
};
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
section {
width: 100%;
height: 100%;
}
table,
td {
width: 40%;
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
button {
cursor: pointer;
font-weight: 700;
}
<!DOCTYPE html>
<html>
<head>
<title>Table of best times</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="javascript/besttime.js"></script>
</head>
<body>
<section>
<table>
<tbody>
<caption>The best times</caption>
<tr>
<td id="firstTimeMin">1</td>
<td id="firstTimeSec">2</td>
</tr>
<tr>
<td id="secondTimeMin">3</td>
<td id="secondTimeSec">4</td>
</tr>
<tr>
<td id="thirdTimeMin">5</td>
<td id="thirdTimeSec">6</td>
</tr>
</tbody>
</table>
<button onclick="timeEntry()">
Enter a new time
</button>
</section>
</body>
</html>
My idea was to simply get the data already in the table using Number or parseInt to get the number value, but either way from the test I've been doing, when I try to get the element from html, it tells me that I get a number type but when I try to use it in an operation it returns NaN. Maybe I'm just stupid, but I've been reading and looking for a day for a way to get the data from the cells as numbers, but aside from Number or parseInt or using a form, I haven't seen a way to do this and it feels like the more I search the less I understand why it doesn't work.
Any help or clue on how to get this done, even it means start back from scratch would be really appreciated.
document.getElementById('firstTimeMin') only get the DOM Element, you should do document.getElementById('firstTimeMin').innerHTML to get the content of the HTML so you'll be able to get the number using parseInt() or Number.
Do the same with every elements.

I add <!DOCTYPE html> and it breaks my code and without it it work perfectly

Every time i add the rats at the top dont fall down. I saw other people had this problem and it had to do with adding px to certain things. i have that in some of my code but i have no clue where else it needs it.
CSS
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Balloons Toss</title>
<meta charset="utf-8" />
<meta name="Author" content="Tyler Chretien" />
<meta name="Author" content="Karishma" />
<meta name="Author" content="Eric Nguygen" />
<meta name="robots" content="noindex, nofollow" />
<style>
#SPAN_1:hover{color:blue;}
#SPAN_1{color:black;}
#SPAN_2:hover{color:blue;}
#SPAN_2{color:black;}
table.center {
margin-left:auto;
margin-right:auto;
width: 560px;
text-align: center;
}
#font-face{
font-family: memes;
src: url(DeterminationSansWeb.woff);
}
body{
font-family: memes, sans-serif;
background-color: black;
}
.blackbox{
color: white;
width: 300px;
}
td{
height: 900px;
}
img, body{
-khtml-user-select: none;
-o-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
img {
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
}
</style>
JavaScript
<script>
var numberOfMonster= 0, setupScore, setupMonster, names=["rat.gif"],
catleft = 325, catright= 250, ratleft, ratright, countElement, howfast=
10, score = 0;
/*This function is the initial setup for the game aka score, sound,
monster spawn */
function myFunction()
{
spawntheMonster( 0 );
document.all.coolscore.innerHTML= 0;
setupScore=setInterval(function(){score++;
document.all.coolscore.innerHTML=score;}, 1000 );
setupMonster=setInterval(function(){spawntheMonster( 0 );}, 3000 );
document.getElementById('sound').play();
}
/*Next four function are deticated for moving the cat and setting
boundaries */
function leftArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.right.substring(element.style.right.length
- 2 , 0 )) > 0 ) {
element.style.right = parseInt(element.style.right) -
20 + 'px';
}
}
function rightArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.right.substring(element.style.right.length -
2
, 0 )) < 480 ) {
element.style.right = parseInt(element.style.right)
+ 20 + 'px';
}
}
function upArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.top.substring(element.style.top.length - 2
,
0 )) > 0 ) {
element.style.top = parseInt(element.style.top) -
20 + 'px';
}
}
function downArrowPressed()
{
var element = document.getElementById("cat");
if(parseInt(element.style.top.substring(element.style.top.length - 2 ,
0 )) < 740 ) {
element.style.top = parseInt(element.style.top) +
20 + 'px';
}
}
/* connects the id's of arrow keys and w,a,s,d to the previous
functions to be able to move */
function movetheguy(event){
switch (event.keyCode) {
case 39:
leftArrowPressed();
break;
case 37:
rightArrowPressed();
break;
case 38:
upArrowPressed();
break;
case 40:
downArrowPressed();
break;
case 68:
leftArrowPressed();
break;
case 65:
rightArrowPressed();
break;
case 87:
upArrowPressed();
break;
case 83:
downArrowPressed();
break;
}
}
/* sets spawn, attributes, and clickablity of the rats */
function spawntheMonster(monster){
var widthrandom = Math.floor(Math.random() * 112 )* 5 - 20;
widthrandom = "position:absolute; right: "+widthrandom+"; top:
000;";
var z = document.createElement("IMG");
z.setAttribute("src", names[monster]);
z.setAttribute("style", widthrandom);
z.setAttribute("width", "40");
z.setAttribute("height", "54");
z.setAttribute("id", numberOfMonster+"mon");
z.setAttribute("onLoad", "setInterval(moveguydown, 100, this);");
z.setAttribute("onClick", "this.style.top=parseInt(this.style.top)-75;");
document.getElementById("back1").appendChild(z);
numberOfMonster++;
}
/* moves the rats */
function moveguydown(moveMonster){
if(parseInt(moveMonster.style.top)>= 900 ){
moveMonster.style.top= -500;
moveMonster.style.right=Math.floor(Math.random() * 112 )* 5 -
20; //check this
}
else
moveMonster.style.top=parseInt(moveMonster.style.top)+howfast;
overlap(moveMonster);
}
/* randomly spawns the rats */
function randomspawn(){
spawntheMonster(Math.floor(Math.random() * names.length));
}
/* This function displays the end screen and resets game*/
function die(){
var highscore=document.all.coolscore.innerHTML;
var count;
for(count= 0 ; count<numberOfMonster; count++){
countElement=document.getElementById(count+"mon");
document.getElementById("back1").removeChild(countElement);
}
numberOfMonster = 0;
document.all.coolscore.innerHTML=
"GAME OVER<br><span onClick='location.reload();'>Click to restart!
</span><br>SCORE: "+score+
"<font size='5'><br>Thanks to<br>Cat By: PRguitarman<br>Sound By: Jay
Man<br>Rats By: Yacht Club Games";
clearInterval(setupScore);
clearInterval(setupMonster);
}
/* Compares hit boxes and checks to see if you die */
function overlap(obj){
catleft =parseInt(cat.style.right)+ 75;
catright=parseInt(cat.style.right);
ratleft =parseInt(obj.style.right)+parseInt(obj.width);
ratright=parseInt(obj.style.right);
cattop =parseInt(cat.style.top);
catbot=parseInt(cat.style.top)+ 150;
rattop =parseInt(obj.style.top)+parseInt(obj.height);
ratbottom=parseInt(obj.style.top);
if(rattop<catbot && ratbottom>cattop && ratright<catleft &&
ratleft>catright)
die();
}
/* Switches difficulty and sound */
function twospeeds(){
if(howfast== 30 ){//fast
back1.style.backgroundImage="url('large0.gif')";
howfast= 10;}
if(howfast== 10){//WAY too fast
back1.style.backgroundImage="url('large2.gif')";
howfast= 30;
document.getElementById('sound').src="sun.mp3";
document.getElementById('sound').play();
}
}
</script>
</head>
html
<body onKeyDown="" onkeyup="movetheguy(event);" >
<table class="center" style="position: relative;">
<tbody><tr>
<td id="back1" style="vertical-align: text-top; font-size:400%;
background-
image: url('large0.gif'); position: relative;">
<div class = "no-copy" id="coolscore">
<span onclick="myFunction();" id="SPAN_1">CLICK HERE
TO START</span>
<span onclick="twospeeds();" id="SPAN_2" style="font-
size:42px;">Click here for Insane mode</span>
<span style="font-size:24px;"><br>Use the Arrow Keys
or WASD to move<br>Click on the rats to move them up</span>
</div>
<br><br><br><br><img alt = "cat" src="cat.gif" width="75" height="150"
id="cat" style="position: absolute; right: 250px; top: 500px">
</td>
</tr>
</tbody>
</table>
<audio id="sound" hidden src="sound.mp3" >
</audio>
<audio id="sound2" hidden src="sun.mp3" >
</audio>
<footer style="border-top: 1px solid blue">
<a href="http://elvis.rowan.edu/~chretient7/"
title="Link to my home page">
Tyler Chretien
</a>
<span style="float: right;">
HTML5 /
<a href="http://jigsaw.w3.org/css-validator/check/referer?profile=css3">
CSS3 </a>
</span>
</footer>
</body>
</html>
https://github.com/Crouton18/game/blob/master/balloon.html
You can check by removing the in the code how it suppose to work. But in general the rats need to be falling down and when the cat gets hit the game ends.
Because the HTML tag is XHTML. Use this doctype instead:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Function not defined, even though I defined it

I’m making a game and a function that I defined says that it’s not defined.
I looked and it said that the other person with the same issue had an extra ) somewhere but I looked and I don’t have that problem.
I don’t have anything extra that is not needed.
<DOCTYPE html>
<html>
<head>
<title>Programing Clicker</title>
<style>
h1{
color:#333;
font-family:helvetica;
font-weight: bold;
font-size:2.5em;
}
h2{
font-size:2em;
position: relative;
left:250px;
display: block;
}
h3{
font-size:1.75em;
position: relative;
left: 250px;
display: block;
}
</style>
</head>
<body>
<center>
<h1>Programing Clicker</h1>
<hr>
</center>
<h2>Skill</h2>
<h3 id="skill_show"></h3>
<h2>Money</h2>
<h3 id = "moneyShow"></h3>
<h2>Language</h2>
<br>
<br>
<p id="timer"></p>
<button onClick = "scriptMake()">Make a script</button>
<script>
var money = 1;
var skill = 1;
var language = 1;
var scriptTime = 100/skill;
var scriptTime2 = scriptTime;
function scriptMake(){
for(var x = 100,x >= 0, x += skill){
document.getElementById("timer").innerHTML = x;
}
}
setInterval(
function showvars(){
document.getElementById("skill_show").innerHTML = skill;
document.getElementById("moneyShow").innerHTML = money;
},1
)
</script>
</body>
your problem is here
for(var x = 100,x >= 0, x += skill){
You need semicolons instead of commas like so
for(var x = 100;x >= 0; x += skill){
Depending on which browser you are using to view the game, look up how to open the console in the browser. It will help you debug these things in a second.

Categories