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');
Related
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" />
I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>
This is where I enter a text:
Upon clicking on the COUNT button, it goes to this page:
My text and word count got displayed. But how do I get the word density of this text using vanilla JavaScript, and actually display it on this page?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
</head>
<body>
<div id="input-page">
<h1>Word Counter</h1>
<form action="">
<textarea id="text" type="text" rows="22" cols="60"></textarea>
<br />
</form>
<button onclick="displayText()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
<h1>Your Text:</h1>
<p id="display-text"></p>
<div id="word-count"></div>
<div id="word-density">
<h1>Word Density:</h1>
</div>
</div>
</body>
<script src="app.js"></script>
</html>
JavaScript:
const displayText = () => {
const inputPage = document.getElementById("input-page");
const countPage = document.getElementById("count-page");
const text = document.getElementById("text");
const textValue = text.value;
if (text.value !== "") { // normal flow will continue if the text-area is not empty
inputPage.style.display = "none";
document.getElementById("display-text").innerText = textValue;
countPage.style.display = "block";
} else { // if the text-area is empty, it will issue a warning.
alert("Please enter some text first.")
}
const countWords = (str) => {
return str.split(" ").length;
};
const wordCount = (countWords(textValue));
const renderWordCount = () => {
const wordCountDiv = document.getElementById("word-count");
wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
};
renderWordCount();
};
For getting the word density like #SimoneRossaini told, simply use a list and save how many times you found each word. This ends up like this for example:
I modified your code and added the word density.
const displayText = () => {
const inputPage = document.getElementById("input-page");
const countPage = document.getElementById("count-page");
const text = document.getElementById("text");
const textValue = text.value;
if (text.value !== "") { // normal flow will continue if the text-area is not empty
inputPage.style.display = "none";
document.getElementById("display-text").innerText = textValue;
countPage.style.display = "block";
} else { // if the text-area is empty, it will issue a warning.
alert("Please enter some text first.")
}
const countWords = (str) => {
return str.split(" ").length;
};
const wordCount = (countWords(textValue));
const renderWordCount = () => {
const wordCountDiv = document.getElementById("word-count");
wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
};
const getWordDensity = (str) => {
let wordList = {};
str.split(/[\s\.,]+/).forEach(word => {
if(typeof wordList[word] == "undefined"){
wordList[word] = 1;
}
else{
wordList[word]++;
}
});
return wordList;
};
const wordDensity = (getWordDensity(textValue));
const renderWordDensity = () => {
const wordDensityDiv = document.getElementById("word-density");
let table = "<table>";
for(let word in wordDensity){
table += "<tr><td>" + word + "</td><td>" + wordDensity[word] + "</td></tr>";
}
table += "</table>";
wordDensityDiv.innerHTML = "<h1> Word Density: </h1>" + table;
};
renderWordCount();
renderWordDensity();
};
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
</head>
<body>
<div id="input-page">
<h1>Word Counter</h1>
<form action="">
<textarea id="text" type="text" rows="22" cols="60"></textarea>
<br />
</form>
<button onclick="displayText()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
<h1>Your Text:</h1>
<p id="display-text"></p>
<div id="word-count"></div>
<div id="word-density"></div>
</div>
</body>
<script src="app.js"></script>
</html>
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>
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>