My Loop work just 2 times(Javascript Dice Game) - javascript

I want to make simple dice game when i press the images,every one of them changed just one time, that does it mean i can change the number 2 times in total. what is the problem?
let dicelenght = document.querySelectorAll('img').length;
for(let i=0; i<dicelenght;i++)
{
let randomNum = Math.floor(Math.random()*6) + 1;
let randomDice = "images/dice" + randomNum + ".png";
let Dice = document.querySelectorAll('img');
Dice[i].addEventListener("click", function(){
Dice[i].setAttribute('src', randomDice);
});
}

You are not generating the random number when the click happens. You have done that just once for every die. Instead you should only generate the random number when the user has clicked.
Also, don't query for the elements in each iteration: just do this once at the top:
let dice = document.querySelectorAll('img');
for (let die of dice) {
die.addEventListener("click", function(){
let randomNum = Math.floor(Math.random()*6) + 1;
let randomDieSrc = "images/dice" + randomNum + ".png";
die.setAttribute('src', randomDieSrc);
});
}

You need to generate the number on click, but please also delegate
document.getElementById("diceDiv").addEventListener("click", function(e) {
const img = e.target.closest("img")
if (img) {
let randomNum = Math.floor(Math.random() * 6) + 1;
img.setAttribute('src', `images/dice${randomNum}.png`);
img.setAttribute('alt', randomNum);
}
});
<div id="diceDiv">
<img id="d1" alt="d1"/><img id="d2" alt="d2"/><img id="d3" alt="d3"/><br>
<img id="d4" alt="d4"/><img id="d5" alt="d5"/><img id="d6" alt="d6"/>
</div>
If you only want them to click once, you can test
const diceDiv = document.getElementById("diceDiv")
diceDiv.addEventListener("click", function(e) {
const img = e.target.closest("img")
if (img) {
if (!img.alt.includes("d")) return; // already clicked
let randomNum = Math.floor(Math.random() * 6) + 1;
img.setAttribute('src', `images/dice${randomNum}.png`);
img.setAttribute('alt', randomNum);
}
});
document.getElementById("reset").addEventListener("click", function(e) {
diceDiv.querySelectorAll("img").forEach(img => img.alt = img.id);
})
<div id="diceDiv">
<img id="d1" alt="d1" /><img id="d2" alt="d2" /><img id="d3" alt="d3" /><br>
<img id="d4" alt="d4" /><img id="d5" alt="d5" /><img id="d6" alt="d6" />
</div>
<input id="reset" type="button" value="Reset" />

Related

html Text content not updating

I'm trying to make an incremental game. but when I test it out the game doesn't increment clicks, everything looks fine. So what am I doing wrong?
Thanks in advance :)
JavaScript Code(in separate file)
//Unused or copied code
// mass += energy;
// btn.innerText = mass + "mass";
//DOM
let btn = document.getElementById("btn");
let img = document.getElementById("img");
//Variables
var mass = 0;
var energy = 1;
var version = 0.1 + 'oab';
//El(s)
img.addEventListener('click', e => {
mass += energy;
let btn.textContent = mass + " Mass";
});
<input type="image" id="img" src="assets/sun.jpg" name="button" alt="clicker" width="250" height="250"><br>
<h1 id='btn'>0 Mass</h1>
There is no need to use let to assign .textContent
let btn = document.getElementById("btn");
let img = document.getElementById("img");
//Variables
var mass = 0;
var energy = 1;
var version = 0.1 + "oab";
//El(s)
img.addEventListener("click", (e) => {
mass += energy;
btn.textContent = mass + " Mass";
});
<input type="image" id="img" src="https://source.unsplash.com/random/" name="button" alt="clicker" width="400" height="100" />
<br />
<h1 id="btn">0 Mass</h1>
#ManasKhandelwal
HTML code:
<body>
<h1 id="btn">0 Mass</h1>
<h1 id="nrg">1 Energy</h1>
<br><br><br>
<input type="image" id="img" src="assets/sun.jpg" name="img" alt="clicker" width="250" height="250">
<br><br>
<div id="spacerock">
<h1>Space Rock</h1>
<div id="rest">
<img src="assets/space_rock.png" alt="space rock" width="32" height="30">
<div id="l&c">
<h2>Cost: 50</h2>
<h2>LvL: 1</h2>
</div>
</div>
</div>
<script src ="js/main.js"></script>
</body>
</html>
Javascript Code:
img.addEventListener('click', (e) => {
mass += sra;
btn.innerHTML = mass + ' Mass';
});
spaceRock.addEventListener('click', (e) => {
if (mass >= srp) {
if (srl <= 12) {
energy += sra;
srl += 1;
srp = srl * 50;
sra += 1.5;
nrg.innerHTML = energy;
} else {
nrg.innerHTML = 'MAX';
}
}
});
const text = document.innerHTML();
const btn = document.querySelector('btn');
const img = document.querySelector('img');
const nrg = document.querySelector('nrg');
const spaceRock = document.querySelector('spacerock');

How to show different image on JavaScript onclick and display the same image on 3rd or 4th click

window.onload = choosePic;
var myPix = new Array("img1.jpg", "img2.jpg", "img3.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
document.getElementById("myPicture2").src = myPix[randomNum];
document.getElementById("myPicture3").src = myPix[randomNum];
}
<img src="img.jpg" width="100" height="100" id="myPicture" alt="some image" />
<img src="img.jpg" width="100" height="100" id="myPicture2" alt="some image" />
<img src="img.jpg" width="100" height="100" id="myPicture3" alt="some image" />
<button id="btn" onclick="choosePic()">Click Hear</button>
I want to show 3 different images from the array. and on 4th or 5th click want to show the same pic.
Something like this?
// gather all <img> elements on page
const imgs = document.querySelectorAll('img');
const imgCount = imgs.length;
// the "Click Here" button
const btn = document.getElementById('btn');
// array of randomly generated image URLs
let imgUrls = [];
let urlsLength;
// number of button clicks
let clickCount;
// initialize the page
function initialize() {
clickCount = 0;
// form array of random image urls from 'picsum.photos'
const randomIndex = Math.floor(Math.random() * 100);
for (let i = 0; i < imgCount * 4; i++) {
imgUrls.push(
`https://picsum.photos/id/${randomIndex+i}/100`);
}
urlsLength = imgUrls.length;
// hide all <img> elements
imgs.forEach(img => {
img.src = "#";
img.style.opacity = "0";
});
// enable the "Click Here" button
btn.disabled = false;
}
// handle "Click Here" button
function buttonClick() {
const iUrlRand = Math.floor(Math.random() * urlsLength);
if (++clickCount < 4) {
// show 3 random images
for (let j = 0; j < imgCount; j++) {
const iImg = (iUrlRand + j) % urlsLength;
imgs[j].src = imgUrls[iImg];
imgs[j].style.opacity = "1";
}
} else if (clickCount < 6) {
// show 1 random image, duplicated in 3 elements
imgs[0].src = imgUrls[iUrlRand];
for (let j = 0; j < imgCount; j++) {
imgs[j].src = imgUrls[iUrlRand];
}
}
if (clickCount === 5) {
// disable button to prevent more than 5 clicks
btn.disabled = true;
}
}
window.onload = initialize;
<body style="background-color: #aaa">
<img src="" width="100" height="100" alt="img 0" />
<img src="" width="100" height="100" alt="img 1" />
<img src="" width="100" height="100" alt="img 2" /><br/>
<button id="btn" onclick="buttonClick()">Click Here</button>
<button onclick="initialize()">Reset</button>
</body>

How can I reduce the repetitive work of this jquery source?

$("#sel1").click(function () {
$("#itemed1").attr("src", "../img/tab_img_01_on.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
$("#itemed2").attr("src", "../img/tab_img_02_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
$("#itemed3").attr("src", "../img/tab_img_03_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
$("#itemed4").attr("src", "../img/tab_img_04_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
});
Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?
You could use a simple combination of selectors.
See sample here or in CodePen:
$(".selector").click(function () {
let index = $(this).data('index');
$(".selector").find("span").removeClass("add");
$(this).find("span").addClass("add");
$(".imgs").each( function(){
$(this).attr("src", `../img/tab_img_0${$(this).data('index')}.png`);
});
$(`.imgs[data-index="${index}"]`).attr("src", `../img/tab_img_0${index}_on.png`);
});
.add {
font-size: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="selector" data-index="1">Sel 1 <span>sample</span></button>
<button class="selector" data-index="2">Sel 2 <span>sample</span></button>
<button class="selector" data-index="3">Sel 3 <span>sample</span></button>
<button class="selector" data-index="4">Sel 4 <span>sample</span></button>
<img data-index="1" class="imgs" />
<img data-index="2" class="imgs" />
<img data-index="3" class="imgs" />
<img data-index="4" class="imgs" />
Obviously, if you are using n index > 10 you should use the padStart function.
Expendable version of same code.
function pad(v) {
return (v.length === 2 ? v : '0' + v);
}
$('[id^=sel]').click(function() {
var total = 4;
var idNumber = $(this).attr('id').match(/\d+/);
for ( i = 1; i <= total; i++ ) {
$('#itemed' + i).attr('src', '../img/tab_img_' + pad(i) + '.png');
$('#sel' + i).find('span').removeClass('add');
}
$('#itemed' + idNumber).attr('src', '../img/tab_img_' + pad(idNumber) + '_on.png');
$(this).find('span').addClass('add');
});
But I think #SnakeDrak approach is correct
This will work up to selects with the number 9. It will need a little more work to make it work with numbers grater then 9
$("[id^=sel]").click(function () { // match every element where the id starts with "sel"
var idNumber = $(this).attr('id').match(/\d+/); // get the number of given id
// reset all src paths from all given elements
$("#itemed1, #itemed2, #itemed3, #itemed4").attr("src", "../img/tab_img_01.png");
// use the idNumber to concatenate the selector and set the src
$("#itemed" + idNumber).attr("src", "../img/tab_img_0"+idNumber+"_on.png");
// remove the add class to all given elements
$("#sel1, #sel2, #sel3, #sel4").find("span").removeClass("add");
// add the "add" class to $(this) element
$(this).find("span").addClass("add");
});
Please refer below code.
$("[id^=sel]").on('click', function() {
var selectionID = ["sel1", "sel2", "sel3", "sel4"];
var itemID = ["itemed1", "itemed2", "itemed3", "itemed4"];
var selectedButton = $(this).attr("value");
$(this).find("span").addClass("add");
var indexID = selectionID.indexOf(selectedButton) + 1;
$("#itemed" + indexID).attr("src", "../img/tab_img_0" + indexID + "_on.png");
selectionID = selectionID.filter(e => e !== selectedButton);
itemID = itemID.filter(e => e !== itemID[indexID - 1]);
for (var i = 0; i < selectionID.length; i++) {
$("#" + selectionID[i]).find("span").removeClass("add");
$("#" + itemID[i]).attr("src", "../img/tab_img_0" + itemID[i].charAt(itemID[i].length - 1) + ".png");
}
});
.add {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button value="sel1" id="sel1"><span>sel1</span></button><br/>
<button value="sel2" id="sel2"><span>sel2</span></button><br/>
<button value="sel3" id="sel3"><span>sel3</span></button><br/>
<button value="sel4" id="sel4"><span>sel4</span></button><br/>
<img src="" id="itemed1">
<img src="" id="itemed2">
<img src="" id="itemed3">
<img src="" id="itemed4">

I want to increment index number each time the button is clicked to make a slider working

i want to increment index number of the image to actually get the size of the current image each time i click the button here is the code:
var next = document.querySelector("#nextBtn");
var prev = document.querySelector("#prevBtn");
var imgContainer = document.querySelector(".imgContainer");
let img = document.querySelectorAll(".imgContainer > img");
i want this var imgIndex = 0; to increment and store the new value which is incremented.
let size = img[imgIndex].clientWidth;
next.addEventListener('click', slideImg);
function slideImg() {
imgContainer.style.transform = "translateX(" + (-size) + "px)";
imgIndex++;
}
Refer this code.
You may not used the image index top of your function / global value. That's what it is again starts from zero.
function slideImg() {
var next = document.querySelector("#nextBtn");
var prev = document.querySelector("#prevBtn");
next.addEventListener('click', slideImg1);
}
var imgIndex = 0;
function slideImg1() {
var imgContainer = document.querySelector(".imgContainer");
let img = document.querySelectorAll(".imgContainer > img");
let size = img[imgIndex].clientWidth;
alert(imgIndex);
img[imgIndex].style.transform = "translateX(" + (-size) + "px)";
imgIndex++;
}
</script>
<body onload="slideImg()">
<input type="button" id="nextBtn" value="+" />
<input type="button" id="prevBtn" value="+" />
<div class="imgContainer">
<img src="file" />
<img src="file" />
</div>
</body>

onclick: picture does not change

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>

Categories