Different Images Based On A Range Of Score - html

I recently was following a youtube tutorial on creating a whack-a-mole type game: https://www.youtube.com/watch?v=toNFfAaWghU.
I followed the code just fine till the end and now I'm wondering if it is possible to set up a system that could detect the score of the user when the time runs out and show different pictures (1-5 star ratings) based a range of scores.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Whack-A-Bear!</title>
<link href='https://fonts.googleapis.com/css?family=Amatic+SC:400,700' rel='stylesheet' type='text/css'>
<link href='https://www.cssfontstack.com/Gill-Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<audio autoplay>
<source src="Outrun - Original Arcade Music.mp3" type="audio/mpeg">
</audio>
<h1>Whack-A-Bear! <span class="score">0</span></h1>
<center><h2>But Not A Hare!!</h2></center>
<div id="timer">
<h2>Timer</h2>
<p id="TimerDisplay">00:15</p>
</div>
<center><button onClick="startGame()">Click Here To Start!</button></center>
<div class="game">
<div class="hole hole1">
<div class="mole"></div>
</div>
<div class="hole hole2">
<div class="mole"></div>
</div>
<div class="hole hole3">
<div class="mole"></div>
</div>
<div class="hole hole4">
<div class="mole"></div>
</div>
<div class="hole hole5">
<div class="mole"></div>
</div>
<div class="hole hole6">
<div class="mole"></div>
</div>
</div>
<script>
/*https://medium.freecodecamp.org/javascripts-var-let-and-const-variables-explained-with-a-story-2038e3c6b2f9 */
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
/*The querySelector() method only returns the first element that matches the specified CSS selectors.
To return all the matches, use the querySelectorAll() method instead.*/
let lastHole;
let timeUp = false;
let score = 0;
//set random timing for the moles to pop up
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
//set random holes for the moles to pop up from the list of our six holes
function randomHole(holes) {
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
// if by chance, we keep getting the same one as the last one, run the function again
if (hole === lastHole) {
//shows that it was about to show you the same hole but didn't so ran the function again
console.log('Ah nah thats the same one bud');
return randomHole(holes);
}
lastHole = hole;
return hole;
}
function peep() {
var imgs = ["yes.png", "Final Hare.png"];
var i = Math.floor(Math.random() * imgs.length);
var raccoon = document.getElementById('raccoon.png');
// these random times refer to how long the mole will stay popped up
const time = randomTime(200, 1000);
const hole = randomHole(holes);
//shows the random home in a random amount of time
console.log(time, hole);
var mole = hole.querySelector(".mole");
mole.style.background = "url('" + imgs[i] + "') bottom center no-repeat";
mole.style.backgroundSize = "60%";
//triggers the CSS to get the mole to come up
hole.classList.add('up');
//makes the mole go away after it has come up => means after the time's up, remove the mole
setTimeout(() => {
hole.classList.remove('up');
//if the time is not up, then run peep () again
if (!timeUp) peep();
}, time);
}
function startGame() {
scoreBoard.textContent = 0;
timeUp = false;
score = 0;
peep();
//a Timeout function will run when time up is true at 10 seconds
setTimeout(() => timeUp = true, 15000)
var sec = 15;
var timer = setInterval(function(){
document.getElementById('TimerDisplay').innerHTML='00:'+sec;
sec--;
if (sec < 0) {
clearInterval(timer);
}
}, 1000);
}
function bonk(e) {
//function bonk will take in an event which will be us clicking each of the moles
//you can simulate a click in JS but here we don't want that to be possible
if(!e.isTrusted) return; // cheater! To prevent a fake click if the event is not trusted, not clicked with mouse
score++;
this.parentNode.classList.remove('up');
scoreBoard.textContent = score;
}
moles.forEach(mole => mole.addEventListener('click', bonk));
</script>
</body>
</html>

Use a switch statement for the image on the end screen such as
switch(true){
case score > firstStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE1.png\")";
break;
case score > secondStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE2.png\")";
break;
case score > thirdStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE3.png\")";
break;
case score > fourthStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE4.png\")";
break;
default:
//because you probably don't want an upper limit on score
document.getElementById("END IMAGE ID").style.backgroundImage = "IMAGE5.png";
}
And you would call that at the end
and because I didn't know the id for the end, i just put END IMAGE ID so that is something you'll have to change.
In the future, please cut your code down to a minimal example. It makes things easier to read for the ones trying to help.

Related

Countdown using astrisk

Currently it shows smallest to biggest. I want it start from biggest to smallest, can't figure it out.
Current output of code
Sample run:
Input to text box: 3
Output in div:
[*]
[**]
[***]
And that’s all folks!
Desired output of code
Sample Run:
Input to text box: 3
Output in div:
[***]
[**
[*]
And that’s all folks!
<!doctype html>
<!—This code will produce a triangle of stars -->
<!-- ================================== -->
<html>
<head>
<title> Countdown </title>
<script type="text/javascript">
function Countdown() {
var count, astrisk;
i=1;
//j=0;
count = parseFloat(document.getElementById('countBox').value);
document.getElementById('outputDiv').innerHTML = '';
astrisk = '*'
while (i<count) {
j=0;
while (j<i) {
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').innerHTML + astrisk ;
j=j+1;
}
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').innerHTML + '<br>';
i=i+1;
}
document.getElementById('outputDiv').innerHTML =
document.getElementById('outputDiv').innerHTML + 'And that\'s all folks!' + '<br>';
}
</script>
</head>
<body>
<p>
Start of the countdown:
<input type="text" id="countBox" size=4 value=10>
</p>
<input type="button" value="Begin Countdown" onclick="Countdown();">
<hr>
<div id="outputDiv"></div>
</body>
</html>
I tried flipping some variables, couldn't exactly get it to do what I want. Most of my attempts have led to my computer crashing, I feel like answer is there, but I can't exactly see it. code isn't properly formatted, spent 2 hours trying to indent correctly, and eventually I gave up.
Get the input, button and p (output)
Add click event to the button
When the button is clicked, get input.value plus 1 since it's automatically decreased at the beginning of the function
Print to the DOM the asterisk repeated by the value (that is decreased every 1 second).
When the value reaches 0, clear the function.
let btn = document.querySelector('button');
let input = document.querySelector('input');
let output = document.querySelector('p');
// Button onclick
btn.addEventListener('click', () => {
// Save the run time (input value + 1) since it's automatically decreased at run-time
let timesRun = Number(input.value) + 1;
// Disable the button when it's counting
btn.disabled = true;
// Repeated function every 1 second
let interval = setInterval(function(){
// Decrease the run time
timesRun -= 1;
// If reaches 0, clear the function
if(timesRun === 0){
btn.disabled = false;
clearInterval(interval);
output.innerHTML = 'TIMEOUT';
// Else? print the * repeated by times remain
} else {
output.innerHTML = '*'.repeat(timesRun);
}
}, 1000);
});
<input type="number" placeholder="Countdown" />
<button>Start</button>
<div>
<p></p>
</div>
Updated with the following conditions:
Check that the input is a valid number and not empty
Accept a number between 1 and 10 (including)
let btn = document.querySelector('button');
let input = document.querySelector('input');
let output = document.querySelector('p');
// Button onclick
btn.addEventListener('click', () => {
// Check it's a valid nubmer and not empty
if(input.value.length === 0 || isNaN(Number(input.value))) {
output.innerHTML = 'Please type a valid number.';
// Check if the number is between 1 and 10
} else if (Number(input.value) <= 0 || Number(input.value) > 10) {
output.innerHTML = 'Please type a number between 1-10';
} else {
// Save the run time (input value + 1) since it's automatically decreased at run-time
let timesRun = Number(input.value) + 1;
// Disable the button when it's counting
btn.disabled = true;
// Repeated function every 1 second
let interval = setInterval(function(){
// Decrease the run time
timesRun -= 1;
// If reaches 0, clear the function
if(timesRun === 0){
btn.disabled = false;
clearInterval(interval);
output.innerHTML = 'TIMEOUT';
// Else? print the * repeated by times remain
} else {
output.innerHTML = '*'.repeat(timesRun);
}
}, 1000);
}
});
<input type="number" placeholder="Countdown" />
<button>Start</button>
<div>
<p></p>
</div>

JS + HTML: Im trying to use the for in or the for each loop instead of the default for loop in my code. But i can`t get it working

**I want to set the background of all objects of the .false class back to the default color before i change the correct class to green **
let objects = document.querySelectorAll('.false');
let myobject = document.querySelector('.correct');
myobject.addEventListener("click", function(){
for (let items in objects)
{
items.style.backgroundColor = "#d9edff";
}
document.getElementById("tr1").innerHTML = "CORRECT!";
document.querySelector(".correct").style.backgroundColor = "green";
});
EDIT: The full code. I needet to put the objects[object] in to let the background color change to default. But now the button that should get green dosnt work anymore...
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
let objects = document.querySelectorAll('.false'); // var mit object durch getElement function gefüllt mit .class
let myobject = document.querySelector('.correct'); // var mit object durch getElement function gefüllt mit .class
myobject.addEventListener("click", function(){
for (object in objects)
{
objects[object].style.backgroundColor = "#d9edff";
}
document.getElementById("tr1").innerHTML = "CORRECT!";
document.querySelector(".correct").style.backgroundColor = "green";
});
for (let i = 0; i < objects.length; i++)
{
objects[i].addEventListener("click", function(){
document.querySelector(".correct").style.backgroundColor = "#d9edff"; //reset correct button
objects[i].style.backgroundColor = "red";
document.getElementById("tr1").innerHTML = "FALSE!";
})
}
// Part2 without saving the check object in a let/var first and adding the eventlistener in 1 go
document.querySelector('.check').addEventListener("click", function(){
let input = document.querySelector("input");
if(input.value.toLowerCase() == "cs50")
{
input.style.backgroundColor = "green";
document.getElementById("tr2").innerHTML = "CORRECT!";
} else {
input.style.backgroundColor = "red";
document.getElementById("tr2").innerHTML = "FALSE!";
}
})
});
</script>
</head>
<body>
<div class="header">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<!-- TODO: Add multiple choice question here -->
<h3>This is the first question. Multiple choice with atleast 3 buttons? Second one is correct! Which one is correct?</h3>
<h4><p id = "tr1"> </p></h4>
<ul>
<button class="false">Click me to change my color to red</button>
<button class="correct">Click me to change my color to green</button>
<button class="false">Click me to change my color to red</button>
</ul>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<h3>This is the second question. What course is this? </h3>
<h4><p id = 'tr2'></p></h4>
<input type="Text" placeholder="Type answer here!">
<button class="check">submit</button>
</div>
</div>
</body>
</html>
querySelector returns NodeList instead of array. That's why you can't use some of array methods. You can use method for...of:
let objects = document.querySelectorAll('.false');
let myobject = document.querySelector('.correct');
myobject.addEventListener("click", function(){
for (let items of objects)
{
items.style.backgroundColor = "#d9edff";
}
document.getElementById("tr1").innerHTML = "CORRECT!";
document.querySelector(".correct").style.backgroundColor = "green";
});

How do I convert this to an OOP structure?

Currently, this codepen I forked displays one tv monitor on the webpage as shown below where the channel button allows the user to toggle different gif's. This gif data is stored as an array in the js file. I want to create multiple tv sets, so I am thinking it may be better to create a TV class and instantiate the TV object n-times through a loop. I am new to OOP in a web dev context, so I haven't yet figured out how to rearchitect the code to accomplish this. Since id's only allow for one HTML element, duplicating the chunk of code below would visually create another tv but without any dynamic features. What then becomes of the tv-body display elements? Would they be enveloped with a show() fx nested with the script's TV class? Thank you so much in advance!
[Cropped Output Displayed Here][1]
HTML
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Vintage Analog TV</title>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><link rel="stylesheet" href="./style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<!-- partial:indexe.partial.html -->
<main>
<div class="tv-set">
<div class="tv-body">
<div class="screen-container">
<canvas class="static" width="380" height="280"></canvas>
<img class="displayed" src="" alt="Nothing" width="380" height="280">
<div class="screen">
<div class="screen-frame"></div>
<div class="screen-inset"></div>
</div>
</div>
<div class="logo-badge">
<div class="logo-text">Bush</div>
</div>
<div class="controls">
<div class="panel">
<div class="screw"></div>
<div class="dial">
<button class="channel dial-label pristine">Channel</button>
</div>
</div>
<div class="vents">
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
</div>
<div class="panel">
<div class="screw"></div>
<div class="dial">
<button class="dial-label" disabled>Volume</button>
</div>
</div>
</div>
</div>
<div class="legs">
<div class="leg"></div>
<div class="leg"></div>
</div>
</div>
</main>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
JS
document.addEventListener("DOMContentLoaded", tv);
// Helper Functions
//returns tagname
jQuery.fn.tagName = function () {
return this.prop("tagName").toLowerCase;
};
// returns nth parent from target element
$.fn.nthParent = function (n) {
var p = this;
for (var i = 0; i < n; i++)
p = p.parent();
return p;
}
phases = [{
channels: ["red", "blue"]
},
{
channels: ["green", "yellow"]
},
{
channels: ["red", "green"]
},
{
channels: ["blue", "green"]
}
]
const container = document.getElementsByTagName("main")[0];
const template = document.getElementsByClassName("tv-set")
for (let i = 0; i < phases.length; i++) {
const clone = template[i].cloneNode(true);
clone.setAttribute("id", "tv-" + (i + 1))
console.log("clone id: ", clone.getAttribute("id"))
clone.setAttribute("data-channel", 0)
clone.setAttribute("name", "tv-" + i)
// clone.style.backgroundColor = phases[i].channels[0]
container.appendChild(clone)
}
function tv() {
let cnvs = document.querySelectorAll(".static");
//Gather all static elements
// let scrns = $(".static").getContext
// console.log("Screen 01: ", scrns)
// var cnv = document.getElementById("static"),
// var cnv = document.querySelector(".static"), //works in place of line above
// Need to establish a boolean array for the isStatic
let c = []
let isStatic_arr = []
// Need to establish a boolean array for the isStatic
cnvs.forEach((cnv) => {
isStatic_arr.push(false)
var c = cnv.getContext("2d"),
cw = cnv.offsetWidth,
ch = cnv.offsetHeight,
staticScrn = c.createImageData(cw, ch),
staticFPS = 30,
// isStatic_arr.push(false),
// isStatic = false,
staticTO,
gifData = [{
// file: "https://i.ibb.co/chSK1Zt/willie.gif",
file: "./media/back-to-school-chacha.gif",
desc: "Stephen Chow Fight Back to School"
// <video controls autoplay>
// <source src="fbts_chacha_sound.mp4" type="video/mp4">
// <source src="movie.ogg" type="video/ogg">
// Your browser does not support the video tag.
// </video>
},
{
file: "https://i.ibb.co/chSK1Zt/willie.gif",
desc: "Steamboat Willie (Mickey Mouse) steering a ship"
},
{
file: "https://i.ibb.co/0FqQVrj/skeletons.gif",
desc: "Spooky scary skeletons sending shivers down your spine"
},
{
file: "https://i.ibb.co/Hpnwgq2/kingkong.gif",
desc: "King Kong waving on Empire State Building",
},
{
file: "https://i.ibb.co/fp0PSjv/tracks.gif",
desc: "Looking at train tracks from behind a train",
},
{
file: "https://i.ibb.co/5FM7BtH/nuke.gif",
desc: "Nuclear explosion at sea",
}
],
gifs = [],
channel = 0;
for (g in gifData) {
gifs.push(new Image());
gifs[g].src = gifData[g].file;
gifs[g].alt = gifData[g].desc;
}
/* Static */
var runStatic = function () {
isStatic = true;
c.clearRect(0, 0, cw, ch);
for (var i = 0; i < staticScrn.data.length; i += 4) {
let shade = 127 + Math.round(Math.random() * 128);
staticScrn.data[0 + i] = shade;
staticScrn.data[1 + i] = shade;
staticScrn.data[2 + i] = shade;
staticScrn.data[3 + i] = 255;
}
c.putImageData(staticScrn, 0, 0);
staticTO = setTimeout(runStatic, 1e3 / staticFPS);
};
runStatic();
/* Channels */
var changeChannel = function (button, idx) {
console.log("Tv-set: ", idx)
console.log("Tv-set- " + idx + "button: " + button)
// var displayed = document.getElementById("displayed");
var displayed = document.querySelectorAll(".displayed")[idx];
var display_parent = $(".displayed")[1]
console.log("Display: ", displayed)
console.log("Display's parent: ", display_parent)
++channel;
if (channel > gifData.length)
channel = 1;
// this.classList.remove("pristine");
button.classList.remove("pristine");
// this.style.transform = `rotate(${channel * 360/(gifData.length + 1)}deg)`;
button.style.transform = `rotate(${channel * 360/(gifData.length + 1)}deg)`;
theCanvas = document.querySelectorAll(".static")[idx]
// cnv.classList.remove("hide");
theCanvas.classList.remove("hide");
displayed.classList.add("hide"); //CAUSING PROBLEMS
if (!isStatic[idx])
runStatic();
setTimeout(function () {
// cnv.classList.add("hide");
theCanvas.classList.add("hide");
displayed.classList.remove("hide");
displayed.src = gifs[channel - 1].src;
displayed.alt = gifs[channel - 1].alt;
isStatic = false;
clearTimeout(staticTO);
}, 300);
};
function iterate(item, index) {
console.log(`${item} has index ${index}`);
}
// const buttons = document.getElementsByClassName("channel dial-label pristine");
// const btns_arr = Array.from(document.querySelectorAll(".channel"))
const buttons = document.querySelectorAll(".channel")
buttons.forEach((btn, i) => {
btn.addEventListener('click', () => changeChannel(btn, i));
});
});
}
[1]: https://i.stack.imgur.com/INtzP.png
[2]: https://i.stack.imgur.com/aOxoQ.png
(11/14/20) #ggirodda, thank you so much for the example. Unfortunately, I am still a bit stuck. Why is it when I use const template = document.getElementsByClassName("tv-body").children[0], I get the error: script_001.js:154 Uncaught TypeError: Cannot read property '0' of undefined
at HTMLDocument.tv (script_001.js:154) Shouldn't the tv-body class have children based on the code snippet below?
(11/14/20) Addressed error above by removing .children[0] but unsure as to why that works and why it was undefined.
(11/19/20) Resolved! Sort of, that is. All tv clones can will run as intended, meaning the static display will remain active on all tv's whose channel button has not been pressed, and the channels can be changed independently. Here were the main changes I made on the original code:
All id's replaced with classes so that they can be accessed and wrapped the "tv-body" and "legs" in a separate div so that they can be cloned as a set.
Gathered all the "tv-set" class elements outside of the tv function() and then performed the setup functions forEach()
Converted a few of the variables e.g canvas, isStatic into arrays so that their states and displays could be toggled independently. I am sure there is more work to be done here as some of the variables may still be shared among the clones.
You can take some inspiration from the code below, the example is less complex but the idea is the same
const tvs = [
{ channels: ["red", "blue"] },
{ channels: ["green", "yellow"] }
]
function changeChannel(idx) {
const tv = tvs[idx]
const tvNode = document.getElementById("tv-" + idx)
const currentChannelIdx = parseInt(tvNode.getAttribute("data-channel"))
const nextChannelIdx = tv.channels[currentChannelIdx + 1] ? currentChannelIdx + 1 : 0;
tvNode.style.backgroundColor = tv.channels[nextChannelIdx]
tvNode.setAttribute("data-channel", nextChannelIdx)
}
const container = document.getElementById("container")
const template = document.getElementById("tv-template").children[0]
for (let i = 0; i < tvs.length; i++) {
const clone = template.cloneNode(true);
clone.setAttribute("id", "tv-" + i)
clone.setAttribute("data-channel", 0)
clone.style.backgroundColor = tvs[i].channels[0]
container.appendChild(clone)
}
const buttons = document.getElementsByClassName("channel-btn")
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', () => changeChannel(i), false);
}
<div id="container"></div>
<div id="tv-template" style="display: none;">
<div class="tv" style="width: 70px; height: 70px; margin-bottom: 20px;">
<button class="channel-btn">next</button>
</div>
</div>

How to set the position of the progress bar?

I have an audio player on a page. I have a custom progress bar that I created. When users click on that progress bar, I want to tell the audio player to start playing at that position. How do I detect the position of where the person clicked in the div and translate that to a position to play the song?
var aud = $('audio')[0];
var index = 0;
$('.play').on('click', function() {
aud.src = $(this).attr('data-url');
index = $(this).index('.play');
if (aud.paused) {
aud.play();
} else {
aud.pause();
}
});
aud.ontimeupdate = function() {
$('.progress-bar-wrapper').hide();
$('.progress-bar-wrapper:eq(' + index + ')').show();
$('.progress:eq(' + index + ')').css('width', aud.currentTime / aud.duration * 100 + '%')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio src="" style="display: none"></audio>
<div class="play" data-url="{{url}}"><img src="/images/play_course.png" /></div>
<div class="progress-bar-wrapper">
<div class="progress"></div>
</div>
You can get the position of the mouse inside the click event.
I have added two variables inside the click event with both the position of the mouse relative to the element itself and the percentage that the click position represent, use them as you see fit.
Note: I added width and height for the progress bar so I can test your code so keep in mind that the progress wrapper needs to be visible and have a width value.
var aud = $('audio')[0];
var index = 0;
$('.play').on('click', function() {
aud.src = $(this).attr('data-url');
index = $(this).index('.play');
if (aud.paused) {
aud.play();
} else {
aud.pause();
}
});
$(".progress-bar-wrapper").on("click", function (e) {
var posX = e.pageX - $(this).offset().left;
var percentage = parseInt((posX / $(this).width()) * 100);
});
aud.ontimeupdate = function() {
$('.progress-bar-wrapper').hide();
$('.progress-bar-wrapper:eq(' + index + ')').show();
$('.progress:eq(' + index + ')').css('width', aud.currentTime / aud.duration * 100 + '%')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio src="" style="display: none"></audio>
<div class="play" data-url="{{url}}"><img src="https://cdn.iconscout.com/icon/premium/png-512-thumb/play-button-1516951-1285078.png" /></div>
<div class="progress-bar-wrapper">
<div class="progress"></div>
</div>

How to make a script execute on page load?

I am trying to create a HTML script that will pick a random number out of a list I have given when someone loads the page. This means if they refresh the page a new number will appear. I know how to generate a script that shows a random word/number when you press a button but it is necessary to make the number generate itself and also it can't be in a wordbox. If anyone can help me with this, I'd appreciate it.
I don't know much about coding but from the information I've gathered, here's what I have constructed:
<html>
<head>
<title></title>
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of random words
var NumberOfWords = 32
var words = new BuildArray(NumberOfWords)
// Use the following variables to
// define your random words:
words[1] = "2,719"
words[2] = "2,718"
words[3] = "2,717"
words[4] = "2,715"
words[5] = "2,713"
words[6] = "2,711"
words[7] = "2,710"
words[8] = "2,709"
words[9] = "2,708"
words[10] = "2,706"
words[11] = "2,704"
words[12] = "2,702"
words[13] = "2,701"
words[14] = "2,700"
words[15] = "2,699"
words[16] = "2,698"
words[17] = "2,696"
words[18] = "2,694"
words[19] = "2,692"
words[20] = "2,690"
words[21] = "2,688"
words[22] = "2,686"
words[23] = "2,685"
words[24] = "2,683"
words[25] = "2,681"
words[26] = "2,678"
words[27] = "2,675"
words[28] = "2,673"
words[29] = "2,671"
words[30] = "2,669"
words[31] = "2,667"
words[32] = "2,664"
function BuildArray(size){
this.length = size
for (var i = 1; i <= size; i++){
this[i] = null}
return this
}
document.addEventListener("DOMContentLoaded",
function PickRandomWord(frm) {
// Generate a random number between 1 and NumberOfWords
var rnd = Math.ceil(Math.random() * NumberOfWords)
// Display the word inside the text box
frm.WordBox.value = words[rnd]
})
//-->
</SCRIPT>
<CENTER>
<FORM NAME="WordForm">
<INPUT TYPE=TEXT SIZE=50 NAME="WordBox"><BR>
</CENTER>
</FORM>
<body>
<big><big><span style="font-weight: bold;">
<br>
<br>
<br>
</span></big></big>
</body>
</html>
The problem is it doesn't work and I don't know why.
You should put your script inside the DOMContentLoaded listener:
document.addEventListener("DOMContentLoaded", function() {
//call your script here
});
Note: IE8 does not support addEventListener.
If you are using jquery, you can use $(document).ready
$(document).ready(function() {
//call your script here
});