I'm working on a slot machine game where i take 3 random numbers and assign them to different images.
However, I can't get my images to display when you click the button to play the game.
I have the stock images there but when you click SPIN it should replace them with new images based on random numbers.
How can I get the new images to display?.
My code:
<html>
<head>
<title>Slots</title>
<link href="../style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="random.js">
function spinslots() {
var lemon = document.getElementById('lemon.jpg');
var donut = document.getElementById('donut.jpg');
var cherry = document.getElementById('cherry.jpg');
var bar = document.getElementById('bar.jpg');
var random_1;
random_1= Math.floor((Math.random()*4 )+ 1);
var random_2;
random_2 = Math.floor((Math.random()*4 )+ 1);
var random_3;
random_3 = Math.floor((Math.random()*4 )+ 1);
if (random_1 == 1) {
document.getElementById("slot_1").src = "lemon.jpg";
}
if (random_1 == 2) {
document.getElementById("slot_1").src = "donut.jpg";
}
if (random_1 == 3) {
document.getElementById("slot_1").src = "cherry.jpg";
}
if (random_1 == 4) {
document.getElementById("slot_1").src = "bar.jpg";
}
if (random_2 == 1) {
document.getElementById("slot_2").src = "lemon.jpg";
}
if (random_2 == 2) {
document.getElementById("slot_2").src = "donut.jpg";
}
if (random_2 == 3) {
document.getElementById("slot_2").src = "cherry.jpg";
}
if (random_2 == 4) {
document.getElementById("slot_2").src = "bar.jpg";
}
if (random_3 == 1) {
document.getElementById("slot_3").src = "lemon.jpg";
}
if (random_3 == 2) {
document.getElementById("slot_3").src = "donut.jpg";
}
if (random_3 == 3) {
document.getElementById("slot_3").src = "cherry.jpg";
}
if (random_3 == 4) {
document.getElementById("slot_3").src = "bar.jpg";
}
if (random_1 == random_2 == random_3) {
alert("Congradulations, you won!");
}
}
</script>
</head>
<body>
<h1>Test your luck! Click the SPIN button</h1>
<p><button value="Spin" onclick="spinslots();"> SPIN </button></p>
<p>
<div class="SlotDiv" id="div_1"><image id="slot_1" src="images/lemon.jpg"></image></div>
<div class="SlotDiv" id="div_2"><image id="slot_2" src="images/cherry.jpg"></image></div>
<div class="SlotDiv" id="div_3"><image id="slot_3" src="images/bar.jpg"></image></div>
</p>
<p>Credits: <div class="OutputBox" type="numeric" id="Credits" size="10">20</div></p>
</body>
</html>
A few things you can improve about the code:
Don't use both src and content in your <script> tag, as this won't work.
Your getElementById calls should use the value from the id attribute, not the src.
You can set the initial value in the declaration line. i.e. var random_1 = Math.floor(...
Use === for comparing values
a === b === c should be a === b && b === c (thanks #jonas-h)
You should reduce code duplication, the code has the same logic repeated multiple times.
You should use <img> not <image> since the latter is obsolete
Since <img> elements have no content, you can use the short version to close them: <img src="..." />
<p> tags cannot contain block (div) elements inside, use divs instead.
Example of refactored code:
function spinslots() {
const images = [
// lemon:
'https://cdn.pixabay.com/photo/2012/04/03/15/07/lemon-25244_960_720.png',
// donut:
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Simpsons_Donut.svg/1024px-Simpsons_Donut.svg.png',
//cherry:
'https://cdn.pixabay.com/photo/2013/07/13/10/23/cherries-157113_960_720.png',
//bar:
'https://cdn.pixabay.com/photo/2012/04/26/20/00/jackpot-42993_960_720.png',
];
const random_1 = Math.floor(Math.random() * 4);
const random_2 = Math.floor(Math.random() * 4);
const random_3 = Math.floor(Math.random() * 4);
document.getElementById("slot_1").src = images[random_1];
document.getElementById("slot_2").src = images[random_2];
document.getElementById("slot_3").src = images[random_3];
if (random_1 === random_2 && random_1 === random_3) {
alert("Congratulations, you won!");
}
}
.SlotDiv {
display: inline-block;
width: 100px;
height: 100px;
}
.SlotDiv img {
width: 100%;
}
<html>
<head>
<title>Slots</title>
</head>
<body>
<h1>Test your luck! Click the SPIN button</h1>
<div>
<button value="Spin" onclick="spinslots();"> SPIN </button>
</div>
<div>
<div class="SlotDiv" id="div_1">
<img id="slot_1" src="images/lemon.jpg" />
</div>
<div class="SlotDiv" id="div_2">
<img id="slot_2" src="images/cherry.jpg" />
</div>
<div class="SlotDiv" id="div_3">
<img id="slot_3" src="images/bar.jpg" />
</div>
</div>
<p>Credits: <span class="OutputBox" type="numeric" id="Credits" size="10">20</span></p>
</body>
</html>
Further enhancements:
note that the alert shows before the images change, due to it being executed synchronously. You can delay the message for a better effect.
the images take some time to show in the initial load, you can preload the images to avoid this.
Related
I'm creating a simple card game that when a player wins the score should increase per win. But whenever I run this code it keeps resetting the score back to 0.
How can I make it so the scores keep increasing +1 if the corresponding player wins?
I've tried the below and it's unfortunately not working with what I have
$(document).ready(function(){
//storing our images, separating them out by suit. Orderimg from lowest to highest cards.
arrClubs=['2_of_clubs.png','3_of_clubs.png', '4_of_clubs.png', '5_of_clubs.png', '6_of_clubs.png', '7_of_clubs.png', '8_of_clubs.png', '9_of_clubs.png', '10_of_clubs.png', 'jack_of_clubs.png','queen_of_clubs.png', 'king_of_clubs.png', 'ace_of_clubs.png']
arrDiamonds=['2_of_diamonds.png','3_of_diamonds.png', '4_of_diamonds.png', '5_of_diamonds.png', '6_of_diamonds.png', '7_of_diamonds.png', '8_of_diamonds.png', '9_of_diamonds.png', '10_of_diamonds.png', 'jack_of_diamonds.png','queen_of_diamonds.png', 'king_of_diamonds.png', 'ace_of_diamonds.png']
arrHearts=['2_of_hearts.png','3_of_hearts.png', '4_of_hearts.png', '5_of_hearts.png', '6_of_hearts.png', '7_of_hearts.png', '8_of_hearts.png', '9_of_hearts.png', '10_of_hearts.png', 'jack_of_hearts.png','queen_of_hearts.png', 'king_of_hearts.png', 'ace_of_hearts.png']
arrSpades=['2_of_spades.png','3_of_spades.png', '4_of_spades.png', '5_of_spades.png', '6_of_spades.png', '7_of_spades.png', '8_of_spades.png', '9_of_spades.png', '10_of_spades.png', 'jack_of_spades.png','queen_of_spades.png', 'king_of_spades.png', 'ace_of_spades.png']
//console.log(arrClubs);
var player1Score = 0;
var player2Score = 0;
//get random suit. 1 = Clubs, 2 = Diamonds, 3 = Hearts, 4 = Spades.
var suitType = Math.ceil(Math.random() * 4)
var card = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
console.log(arrClubs[card])
selectedCard = arrClubs[card]
} else if(suitType == "2"){
console.log(arrDiamonds[card])
selectedCard = arrDiamonds[card]
} else if (suitType == "3"){
console.log(arrHearts[card])
selectedCard = arrHearts[card]
} else {
console.log(arrSpades[card])
selectedCard = arrSpades[card]
}
document.getElementById('p1Card').src = "./images/cards/" + selectedCard
//Player 2 Randomly Selected Card:
var suitType = Math.ceil(Math.random() * 4)
var card2 = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
// console.log(arrClubs[card2])
selectedCard = arrClubs[card2]
} else if(suitType == "2"){
// console.log(arrDiamonds[card2])
selectedCard = arrDiamonds[card2]
} else if (suitType == "3"){
//console.log(arrHearts[card2])
selectedCard = arrHearts[card2]
} else {
//console.log(arrSpades[card2])
selectedCard = arrSpades[card2]
}
document.getElementById('p2Card').src = "./images/cards/" + selectedCard;
if (card < card2){
player2Score++;
document.getElementById('player2Results').value = player2Score;
// alert("Player 2 Wins")
} else if (card > card2){
player1Score++;
document.getElementById('player1Results').value = player1Score;
// alert("Player 1 wins")
} else {
// alert("TIE!")
console.log('Tie!');
}
})
<!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>War</title>
</head>
<body>
<div> Game</div>
<img src="./images/cards/black_joker.png" id="p1Card">
<img src="./images/cards/red_joker.png" id="p2Card">
<input type="text" readonly id="player1Results"/>
<input type="text" readonly id="player2Results"/>
<button id="play">Play</button>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="./js/index.js"></script>
</body>
</html>
Most likely you are setting player1Score and player2Score back to 0 each time you run it. Here's a working example:
const runGame = (() => {
var player1Score = 0;
var player2Score = 0;
return () => {
const card = Math.random();
const card2 = Math.random();
if (card < card2){
player2Score++;
console.log('Player 2 Wins! Score: ' + player2Score);
document.getElementById('p2').value = player2Score;
} else if (card > card2){
player1Score++;
console.log('Player 1 Wins! Score: ' + player1Score);
document.getElementById('p1').value = player1Score;
} else {
console.log('Tie!');
}
}
})();
document.getElementById('play').addEventListener('click', runGame);
<div id="player1Results"></div>
<div id="player2Results"></div>
<input type="text" readonly id="p1"/>
<input type="text" readonly id="p2"/>
<button id="play">Play</button>
I am new to JS, I want to the code to display number of attempts made, number of guesses remaining in this simple game. I have gotten lost in the code and I don't know what I am not doing right. The const remainingAttempts returns undefined yet I want to subtract number of attempts made from maxNumberOfAttempts.
const guessInput = document.getElementById("guess");
const submitButton = document.getElementById("submit");
const resetButton = document.getElementById("reset");
const messages = document.getElementsByClassName("message");
const tooHighMessage = document.getElementById("too-high");
const tooLowMessage = document.getElementById("too-low");
const maxGuessesMessage = document.getElementById("max-guesses");
const numberOfGuessesMessage = document.getElementById("number-of-guesses");
const correctMessage = document.getElementById("correct");
let targetNumber;
let attempts = 0;
let maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = "";
} else {
tooHighMessage.style.display = ""; //replaced else condition statement
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts === maxNumberOfAttempts) {
maxGuessesMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = "";
resetButton.style.display = "";
}
function hideAllMessages() {
/*replaced elementIndex <= messages.length to elementIndex < messages.length*/
for (let elementIndex = 0; elementIndex < messages.length; elementIndex++) {
messages[elementIndex].style.display = "none"; //removed [elementIndex]
}
// for (let message in messages.value) {
// //used for..in to iterate through the HTML collection
// message.style.display = "none";
// }
}
function setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabled = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = "none";
}
submitButton.addEventListener("click", checkGuess);
resetButton.addEventListener("click", setup);
setup();
main {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin: auto;
}
#guess {
width: 5em;
}
#reset {
margin: 20px;
}
<!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 href="guess.css" rel="stylesheet" />
<title>Number Guesser</title>
</head>
<body>
<main>
<h1>Guessing Game</h1>
<p>
I'm thinking of a number from 1 to 99! Can you guess it in 5 tries or
less?
</p>
<div>
<input type="number" id="guess" min="1" max="99" />
<button id="submit">Submit Guess</button>
</div>
<div>
<p class="message" id="number-of-guesses"></p>
<p class="message" id="too-high">You guessed too high. Try again.</p>
<p class="message" id="too-low">You guessed too low. Try again.</p>
<p class="message" id="max-guesses">
You reached the max number of guesses
</p>
<p class="message" id="correct">
Congratulations, You guessed correctly! <br />
Would you like to play again?
</p>
</div>
<button id="reset">Reset</button>
</main>
<script src="guess.js"></script>
</body>
</html
just increment attempts as attempts++; below const remainingAttempts = maxNumberOfAttempts - attempts;. this should solve the no. of attempts part.
In setup(), when you reset the number of attempts, you should be setting it to 5: maxNumberOfAttempts = 5;
Additionally, in checkGuess(), you should:
Make sure to decrease the number of attempts with each guess. Add maxNumberOfAttempts-- at the top of the function.
At the bottom of if (guess !== targetNumber), you can replace the variable in the message from ${remainingAttempts} to ${maxNumberOfAttempts}
, since maxNumberOfAttempts is now keeping track of the amount of attempts remaining.
Lastly, the next if statement can check if the user is out of attempts with if (maxNumberOfAttempts === 0) {...}
This eliminates the need to use 3 different 'attempt' variables since you're resetting back to '5' at each instance of setup() anyway.
I am trying to make a simple web page in which when we enter the text value in the textbox, and as soon as a user inserts a comma between the two texts, a new button gets generated. When the user presses the enter key, the buttons class should toggle between warning and danger.
I am able to achieve it so I also tried to add a delay, but the problem is all buttons class toggling takes place together and not one by one in a random manner. To create a random toggling sequence I created a random permutation of numbers for it, but since all buttons classes are toggling simultaneously I am not getting the required result.
The required result is that first for one buttons toggling should be completed and then for another button - how can I achieve this?
let element = document.querySelector('.textarea');
let cont = document.querySelector('.groupofbtns');
let lastlen = 0;
const pause = (timeoutMsec) => new Promise(resolve => setTimeout(resolve, timeoutMsec))
async function main(grp) {
// here is the delay I am trying to create between toggling but it is executing for all buttons simultaneously.
grp.classList.remove("btn-warning");
grp.classList.add("btn-danger");
await pause(3 * 1000)
grp.classList.remove("btn-danger");
grp.classList.add("btn-warning");
}
element.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
let grp = document.querySelectorAll('.btn')
let l = grp.length - 1, arr = [];
console.log(grp.length)
do {
let num = Math.floor(Math.random() * l + 1);
arr.push(num);
arr = arr.filter((item, index) => {
return arr.indexOf(item) === index
});
} while (arr.length < l);
// console.log(arr);
arr.push(0)
for (let i = 0; i <= l; i++) {
main(grp[arr[i]])
}
}
else if (event.keyCode === 8) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
let grp = document.querySelectorAll('.btn');
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
if (b.length < strArr.length) {
cont.removeChild(grp[grp.length - 1]);
lastlen--;
}
f = b[b.length - 1];
}
if (grp.length == b.length)
grp[grp.length - 1].innerText = `${f}`;
else {
let diff = grp.length - b.length
let i = 0;
while (diff > 0) {
cont.removeChild(grp[grp.length - 1 - i]);
i++;
diff--;
lastlen--;
}
}
}
});
element.addEventListener('input', function (event) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
f = b[b.length - 1];
if (event.keyCode !== 8) {
if (strArr.length > lastlen) {
let butt = document.createElement('button');
butt.classList.add('btn')
butt.classList.add('btn-warning')
//butt.classList.add('container')
butt.classList.add('active')
butt.innerText = `${f}`
cont.appendChild(butt)
lastlen = strArr.length
//cont.innerHTML += `<button type="button" class="btns" >${f}</button>`;
}//element.value = val;
else {
let b = document.querySelectorAll('.btn')
b[b.length - 1].innerText = `${f}`
}
}
}
})
.h
{
display:flex;
flex-direction: column;
width: 50%;
margin-top:30%;
align-items: center;
text-align: center;
}
.lab
{
color:white;
}
.btn
{
margin: 0.8% 0.8%;
}
.groupofbtns
{
width:50%;
margin-top: 2%;
align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Random color picker</title>
<link rel="stylesheet" href="randomcolorcss.css">
</head>
<body style="background-color: blue;">
<div class="container h">
<div class="input-group">
<label for="text" class="lab">Enter your choices here separate them with
commas, Press
Enter when you are
done</label>
<br>
<textarea cols="5" rows="5" class=" textarea form-control" placeholder="Enter Choices here" name="text"
style="width: fit-content; display: block;"></textarea>
</div>
</div>
<div class="groupofbtns container">
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
crossorigin="anonymous"></script>
<script src="randomcolor.js"></script>
</body>
</html>
This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');
My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>