For my collage assignment i need to create a html webpage where if you press the button yes it displays a number and a corresponding image. i have figured out how to create the random number but cannot get the corresponding image to show up when the button in pressed. i am very new to this and any help would be appreciated
This is the java script
function randomNumber() {
var ranNumgen = Math.floor((Math.random() * 6) + 1);
}
console.log("randomNumber");
if ("number" == 1) {
document.getElementById('img1').src = "image/dice1.jpg";
} else if ("number" == 2) {
document.getElementById('img1').src = "image/dice2.jpg";
} else if ("number" == 3) {
document.getElementById("img1").src = "image/dice3.jpg"
} else if ("number" == 4) {
document.getElementById("img1").src = "image/dice4.jpg";
} else if ("number" == 5) {
document.getElementById("img1").src = "image/dice5.jpg";
} else if ("number" == 6) {
document.getElementById("img1").src = "image/dice6.jpg";
}
<head>
<title></title>
<button id="b" onclick="ranNumgen()"> Yes </button>
<button onclick="Num2button()">No</button>
</head>
<body>
<p id="number"> </p>
And this is all my code
<!DOCTYPE html>
<html>
<head>
<title></title>
<button id="b" onclick="ranNumgen()"> Yes </button>
<button onclick="Num2button()">No</button>
</head>
<body>
<p id="number"> </p>
<script type="text/javascript">
function randomNumber() {
var ranNumgen = Math.floor((Math.random() *6) +1);
}
console.log("randomNumber");
if ("number" ==1 ) {
document.getElementById('img1').src ="image/dice1.jpg";
}
else if ("number" ==2) {
document.getElementById('img1').src ="image/dice2.jpg";
}
else if ("number"==3) {
document.getElementById("img1").src="image/dice3.jpg"
}
else if ("number"==4) {
document.getElementById("img1").src="image/dice4.jpg";
}
else if ("number"==5) {
document.getElementById("img1").src="image/dice5.jpg";
}
else if ("number"==6) {
document.getElementById("img1").src="image/dice6.jpg";
}
function Num2button() {
var button2 = "Are you sure"
alert(button2);
}
</script>
</body>
</html>
You can put your logic to assign the picture in your randomNumber function, the best would be to rename it to something like generateRandomPicture.
Then you need an element with the id you have specified and
also I would recommend that you use an eventListener instead of doing the inline scripting.
You can add .addEventListener() to your element.
document.getElementById('b').addEventListener('click', randomNumber);
document.getElementById('b').addEventListener('click', randomNumber);
function randomNumber() {
let number = Math.floor((Math.random() * 6) + 1);
if (number == 1) {
document.getElementById('img1').src = "image/dice1.jpg";
} else if (number == 2) {
document.getElementById('img1').src = "image/dice2.jpg";
} else if (number == 3) {
document.getElementById("img1").src = "image/dice3.jpg"
} else if (number == 4) {
document.getElementById("img1").src = "image/dice4.jpg";
} else if (number == 5) {
document.getElementById("img1").src = "image/dice5.jpg";
} else if (number == 6) {
document.getElementById("img1").src = "image/dice6.jpg";
}
}
<head>
<title></title>
</head>
<body>
<p id="number"> </p>
<img id="img1"></img>
<button id="b"> Yes </button>
<button onclick="Num2button()">No</button>
</body>
I'm aware that the question is already answered and that you are new to this but this is a more scalable approach and looks a bit cleaner.
NOTE: This snippet assumes the images in the array in the correct order, from 1 to N.
let images = [
'https://via.placeholder.com/10',
'https://via.placeholder.com/20',
'https://via.placeholder.com/30',
'https://via.placeholder.com/40',
'https://via.placeholder.com/50',
]
function setRandomImage() {
let index = Math.floor(Math.random() * images.length);
document.getElementById('img').src = images[index];
document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
As per epascarello's comment, this does not rely on the order of the images but they do have to be in the array.
var images = [
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
'https://via.placeholder.com',
]
function setRandomImage() {
let index = Math.floor(Math.random() * images.length) + 1;
document.getElementById('img').src = images[index - 1] + '/' + index + '0';
document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
And if you always have a static number of images which are properly named you can even do away with the images array.
function setRandomImage() {
let rand = Math.floor(Math.random() * 6) + 1;
document.getElementById('img').src = 'https://via.placeholder.com/' + rand + '0';
document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
This question in HTML asks for the user to enter a number 1-5 and then it will show the amount of numbers entered as a picture of a dice with question marks on them. No matter what number I put in I will always get 6 dice to show with question marks. How do I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
text-align: center;
}
img {
height: 150px;
}
</style>
</head>
<body>
<h1>Click the button to see the roll of a die randomly selected</h1>
<script>
Val = window.prompt("Enter the number of dice to play with (1-5)");
<!--if user enters a number <= 1 val ==1-->
if(Val == 1 || Val <= 1){
Val = 1;
}
else if(Val == 2){
Val = 2;
}
else if(Val == 3){
Val = 3;
}
else if(Val == 4){
Val = 4;
}
<!--if user enters anything thats not 1-4 val = 5-->
else Val = 5;
function roll() {
var randomDie = Math.floor(Val*Math.random()) + 1;
var RandomNum = Math.floor(6*Math.random()) + 1;
document.getElementById('dieImg' + randomDie).setAttribute("src","dieImages/die" + RandomNum + ".jpg");
document.getElementById('dieImg' + randomDie).style.display="inline";
document.getElementById('display').innerHTML = "Die " + randomDie + " was selected and rolled to show " + RandomNum;
}
</script>
<!--Show question mark die-->
<img id="dieImg1" src="dieImages/question-mark-dice.jpg">
<img id="dieImg2" src="dieImages/question-mark-dice.jpg">
<img id="dieImg3" src="dieImages/question-mark-dice.jpg">
<img id="dieImg4" src="dieImages/question-mark-dice.jpg">
<img id="dieImg5" src="dieImages/question-mark-dice.jpg">
<hr>
<button type="button" onclick="roll()">Click to Roll</button>
<p id="display">--</p>
</body>
</html>
This is what the application shows when I put in 3,
This is what I want the output to be,
First of all you do not need to re-assign every value
if(Val == 1 || Val <= 1){
Val = 1;
}
else if(Val == 2){
Val = 2;
}
else if(Val == 3){
Val = 3;
}
else if(Val == 4){
Val = 4;
}
this works same as above
//if user enters a number <= 1 val ==1
if (Val < 1) {
Val = 1;
}
//if user enters anything thats not 1-4 val = 5
if (Val > 4) {
Val = 5
}
Second,
it's showing the 5 images everytime because you have mentioned that in the HTML, you need to create the img element dynamically using createElement using a loop.
let img = document.createElement('img');
img.src = "dieImages/question-mark-dice.jpg";
img.id = "dieImg" + i;
let dices = document.getElementById("dices");
dices.appendChild(img);
I re-wrote your example, which is working as you are expecting.
Val = window.prompt("Enter the number of dice to play with (1-5)");
//if user enters a number <= 1 val ==1
if (Val < 1) {
Val = 1;
}
//if user enters anything thats not 1-4 val = 5
if (Val > 4) {
Val = 5
}
for (i = 1; i <= Val; i++) {
let img = document.createElement('img');
img.src = "dieImages/question-mark-dice.jpg";
img.id = "dieImg" + i;
let dices = document.getElementById("dices");
dices.appendChild(img);
}
function roll() {
var randomDie = Math.floor(Val * Math.random()) + 1;
var RandomNum = Math.floor(6 * Math.random()) + 1;
var diceElement = document.getElementById('dieImg' + randomDie);
diceElement.setAttribute("src", "dieImages/die" + RandomNum + ".jpg");
diceElement.style.display = "inline";
document.getElementById('display').innerHTML = "Die " + randomDie + " was selected and rolled to show " + RandomNum;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
text-align: center;
}
img {
height: 150px;
}
</style>
</head>
<body>
<h1>Click the button to see the roll of a die randomly selected</h1>
<!--Show question mark die-->
<div id="dices">
</div>
<hr>
<button type="button" onclick="roll()">Click to Roll</button>
<p id="display">--</p>
</body>
</html>
First off, thank you for reading this question. With this javascript code, I'm trying to implement a 4x4 slide number puzzle, which looks like this when completed. :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 [blank]
Each number are represented by .gif number files which are on the same folder where this HTML file is.
When a user clicks "START" button below the puzzle, it shuffles pieces by repetitively swapping randomly chosen two pieces. (shuffle function)
When a user clicks a piece adjacent to the blank piece then it swaps the two. (movePiece function)
But the problem is when I click the START button and the piece adjacent to the blank piece, nothing happens.. even though except for this code's logic and algorithm is not different from the answer that my instructor's given and I can't find where is causing this problem.
Can anyone help me find out where is wrong with this code?
Any advice would be much appreciated.
<html>
<head>
<title>15 Puzzle Game</title>
<meta name="generator" content="Microsoft FrontPage 4.0" charset="UTF-8">
<script language="JavaScript">
var completed=true;
function tokenize(sep,str){
tokens = new Array();
i=0;
while(1)
{
idx=str.indexOf(sep);
if(idx == -1)
{
if(str.length>0)
{
tokens[i]=str;
}
break;
}
tokens[i++]=str.substring(0,idx);
str=str.substr(idx+1);
}
return tokens;
}
function getX(idx)
{
var rest=idx-Math.floor(idx/4)*4;
return (rest==0)?4:rest;
}
function getY(idx)
{
return Math.floor((idx-1)/4)+1;
}
function getIndex(x,y)
{
return x+(y-1)*4;
}
function newDirection(pos)
{
var dir;
if ((pos==2)||(pos==3)) dir=(Math.floor(Math.random()+0.5)==0)?-1:1;
else dir=(pos==1)?1:-1;
return (pos+dir);
}
function newIndex(idx)
{
var x,y;
x=getX(idx);
y=getY(idx);
if (Math.floor(Math.random()+0.5)==0) x=newDirection(x);
else y=newDirection(y);
return getIndex(x,y);
}
function isComplete()
{
if(completed) return 0;
for(var i = 1; i <= document.images.length; i++){
if(document.images[i-1].src != i+".gif") return 0;
}
return 1;
}
function getNum(idx){
var index = idx - 1;
var token[] = tokenize("/",document.images[index].src);
var numOfTokens = tokenize("/",document.images[index].src).length;
var num = tokenize(".", token[numOfTokens-1])[0];
return Number(num);
}
function shuffle()
{
var puzzles=new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
iter=Math.floor(Math.random()*200+0.5)+100;
for (i=0;i<iter;i++)
{
var ranNum = Math.floor(Math.random()*16)+1;
var newNum = newIndex(ranNum);
var temp = puzzles[ranNum-1];
puzzles[ranNum-1] = puzzles[newNum-1];
puzzles[newNum-1] = temp;
}
}
for(i=1;i<document.images.length+1;i++){
document.images[i-1].src = ""+puzzles[i-1]+".gif";
}
completed = false;
}
function movePiece(idx)
{
x = getX(idx);
y = getY(idx);
var flag = 0;
var tempIdx;
for(i=-1; i<=1 ; i=i+2){
if ((x==2)||(x==3)) dir=i;
else dir=(x==1)?1:-1;
var tmpx= (x+dir);
tempIdx = getIndex(tmpx,y);
if(getNum(tempIdx) == 16){ flag = 1; midx=tempIdx; }
}
for(i=-1; i<=1 ; i=i+2){
if ((y==2)||(y==3)) dir=i;
else dir=(y==1)?1:-1;
var tmpy= (y+dir);
tempIdx = getIndex(x,y);
if(getNum(tempIdx) == 16){ flag = 1; midx=tempIdx; }
}
if (flag == 1){
document.images[midx-1].src = document.images[idx-1].src;
document.images[idx-1].src = "16.gif";
}
if(isComplete()) alert('Congratulation!');
completed = true;
}
</script>
</head>
<body bgcolor="silver" text="black" link="#0000EE" vlink="#551A8B" alink="red">
<h2 align="center">
15 Puzzle</h2>
<div align="center">
<table border>
<tr>
<td width="50%" align="center">
<script language="JavaScript">
with(window.document)
{
open();
writeln('<table border=1 cellpadding=0 cellspacing=1>');
for(var i=1;i<17;i++)
{
if(i==1 || i==5 || i==9 || i==13 )
{
writeln('<tr>');
}
writeln(' <td width=49 height=49>');
writeln(' <a href=JavaScript:movePiece('+i+');>');
writeln(' <img src=',i,'.gif border=0 width=49 height=49 name=i',i,'></a>');
writeln(' </td>');
if(i==4 || i==8 || i==12 || i==16 )
{
writeln('</tr>');
}
}
writeln('</table>');
close();
}
</script>
</td>
</tr>
</table>
</div>
<p align="center">
<br>
</p>
<form method="get">
<p align="center">
<input type="button" value="START" onClick="shuffle()"></p>
</form>
</body>
</html>
javascript
and this is working code
<html>
<head>
<title>15 Puzzle Game</title>
<meta charset="UTF-8">
<script language="JavaScript">
var completed=true;
function tokenize(sep,str)
{
tokens = new Array();
i=0;
while(1)
{
idx=str.indexOf(sep);
if(idx == -1)
{
if(str.length>0)
{
tokens[i]=str;
}
break;
}
tokens[i++]=str.substring(0,idx);
str=str.substr(idx+1);
}
return tokens;
}
function getX(idx)
{
var rest=idx-Math.floor(idx/4)*4;
return (rest==0)?4:rest;
}
function getY(idx)
{
return Math.floor((idx-1)/4)+1;
}
function getIndex(x,y)
{
return x+(y-1)*4;
}
function newDirection(pos)
{
var dir;
if ((pos==2)||(pos==3)) dir=(Math.floor(Math.random()+0.5)==0)?-1:1;
else dir=(pos==1)?1:-1;
return (pos+dir);
}
function newIndex(idx)
{
var x,y;
x=getX(idx);
y=getY(idx);
if (Math.floor(Math.random()+0.5)==0) x=newDirection(x);
else y=newDirection(y);
return getIndex(x,y);
}
function isComplete() {
if(completed)
return false;
var prev = getPiece(1);
for(var i = 2; i < 17; i++) {
var current = getPiece(i);
if(current != prev+1)
return false;
prev = current;
}
return true;
}
function shuffle()
{
var puzzles=new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
iter=Math.floor(Math.random()*200+0.5)+100;
var blank = 15;
for (i=0; i<iter; i++)
{
var move = newIndex(blank+1)-1;
var t = puzzles[blank];
puzzles[blank] = puzzles[move];
puzzles[move] = t;
blank = move;
}
for(i = 0; i < 16; i++)
document.images[i].src = ""+puzzles[i]+".gif";
completed = false;
}
function movePiece(idx)
{
var current = getPiece(idx);
if(current == 16)
return;
var x = getX(idx);
var y = getY(idx);
var flag=false, midx=idx;
var dx = [0, 0, -1, 1], dy = [-1, 1, 0, 0];
for(var i = 0; i < 4; i++) {
if(1 <= x+dx[i] && x+dx[i] <= 4 && 1 <= y+dy[i] && y+dy[i] <= 4) {
if(getPiece(getIndex(x+dx[i], y+dy[i])) == 16) {
flag = true;
midx = getIndex(x+dx[i], y+dy[i]);
break;
}
}
}
if(flag) {
var t = document.images[idx-1].src;
document.images[idx-1].src = document.images[midx-1].src;
document.images[midx-1].src = t;
}
if(isComplete()) {
alert("Congratulation!");
completed = true;
}
}
function getPiece(idx) {
idx--;
var len = tokenize("/", document.images[idx].src).length;
return Number(tokenize(".", tokenize("/", document.images[idx].src)[len-1])[0]);
}
</script>
</head>
<body bgcolor="silver" text="black" link="#0000EE" vlink="#551A8B" alink="red">
<h2 align="center">
15 Puzzle</h2>
<div align="center">
<table border>
<tr>
<td width="50%" align="center">
<script language="JavaScript">
with(window.document)
{
open();
writeln('<table border=1 cellpadding=0 cellspacing=1>');
for(var i=1;i<17;i++)
{
if(i==1 || i==5 || i==9 || i==13 )
{
writeln('<tr>');
}
writeln(' <td width=49 height=49>');
writeln(' <a href=JavaScript:movePiece('+i+');>');
writeln(' <img src=',i,'.gif border=0 width=49 height=49 name=i',i,'></a>');
writeln(' </td>');
if(i==4 || i==8 || i==12 || i==16 )
{
writeln('</tr>');
}
}
writeln('</table>');
close();
}
</script>
</td>
</tr>
</table>
</div>
<p align="center">
<br>
</p>
<form method="get">
<p align="center">
<input type="button" value="START" onClick="shuffle()"></p>
</form>
</body>
</html>
The code you provided isn't a good read, so I've created my own version in React. I hope it'll help you to figure things out or at least inspire you to learn React.
https://codesandbox.io/s/wq8n9k5jr7
So my HTML is:
<!DOCTYPE>
<head>
<script src="js/problem1.js"></script>
</head>
<body>
<input id="clickMe" type="button" value="Problem #1" onclick="problem1();" />
<script src="js/problem1.js"></script>
</body>
The script I am trying to run is:
var counter = 0
var total = 0
var start = prompt("Enter a number here to find the sum of all numbers that are:\n-Between 0 and your number\n-Divisible by 3 or 5")
function problem1(start) {
for (counter = 0; counter < start; counter++) {
if (counter < start) {
if (counter % 3 == 0) {
total += counter;
}
else if (counter % 5 == 0) {
total += counter;
}
}
else if (counter == start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
else {
alert(total);
}
}
}
}
The problem I am running into is that right now the script runs on page load and instantly gives me a prompt for creating the start variable. After entering an integer and clicking Ok the prompt window disappears and nothing happens. I do realize that the script is running on its own because it is called in the <head>. Problem is I don't know how else to call it, like on button click. I don't want to use JQuery. I have seen lots of answers like this one but I am looking for something that doesn't require JQuery. How would I accomplish this?
UPDATE
Thank you for the help. Now I have stumbled upon a second problem. I can't get the script to run or display the alert (not sure which)
put your prompt inside the problem function
function problem1() {
var counter = 0
var total = 0
var start = prompt("Enter a number here to find the sum of all numbers that are:\n-Between 0 and your number\n-Divisible by 3 or 5")
for (counter = 0; counter < start; counter++) {
if (counter < start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
}
else if (counter == start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
else {
alert(total);
}
}
}
}
<!DOCTYPE>
<head>
<script src="js/problem1.js"></script>
</head>
<body>
<input id="clickMe" type="button" value="Problem #1" onclick="problem1();" />
<script src="js/problem1.js"></script>
</body>
I am trying to learn javascript by following this exercise from MDN website Learn JavaScript
here is my final code for the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
</head>
<body>
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or less. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess:</label>
<input type="text" id="guessField" class="guessField" autofocus>
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</body>
<script>
// Your JavaScript goes here
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector(".guesses");
var lastResult = document.querySelector(".lastResult");
var lowOrHi = document.querySelector(".lowOrHi");
var guessField = document.querySelector(".guessField");
var guessSubmit = document.querySelector(".guessSubmit");
var test; //used for creating new reset button
var count = 1; // counter for counting user input
function checkGuess() {
//alert('checkGuess is called');
var value = Number(guessField.value);
if (count === 1) {
guesses.textContent = "Previous guesses :"
}
guesses.textContent += value + ' ';
if (value === randomNumber) {
lastResult.textContent = "congratulation u successfully guessed the number";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
left = 1;
setGameOver();
} else if (count === 10) {
lastResult.textContent = "game over"
lastResult.style.backgroundColor = "red";
left = 1;
setGameOver();
} else {
lastResult.textContent = "WRONG";
lastResult.style.backgroundColor = "red";
if (value < randomNumber) {
lowOrHi.textContent = "too low";
} else {
lowOrHi.textContent = "too high";
}
}
count++;
guessField.value = '';
}
guessSubmit.addEventListener("click", checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
test = document.createElement('button');
test.textContent = "restart game";
document.body.appendChild(test);
test.addEventListener('click', resetGame);
}
function resetGame() {
count = 1;
var resetParas = document.querySelectorAll('.resultParas');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
test.parentNode.removeChild(test);
}
</script>
</html>
But when i try to run the game and use the reset game button to restart the game then i am not able to manipulate guesses,lastResult and lowOrHi elements using textContent and backgroundColor properties.
Your blanking out everything inside .resultParas.. And this will include all you <p> tags. IOW: after doing that they have disappeared from the DOM, you can see this say in chrome inspector that .resultPara's after clicking reset game is now blank, and all your p tags have gone.
I think what you really want to do, is blank out the children (the p tags)..
You don't need querySelectorAll either, as in your case there is only the one.
var resetParas = document.querySelector('.resultParas');
for(var i = 0 ; i < resetParas.children.length ; i++) {
resetParas.children[i].textContent = '';
}