Control if object is clicked or not in if statement - javascript

I'm building a small memory game. Where the user is presented by different objects that are displayed one at a time (which is done by an animation). The user can choose or not choose to click an object. The user is presented with a list indicating which objects should not be clicked, if the user clicks an object that should be clicked he gets one point. If the user decides to not click on a faulty object he should be rewarded one point as well. And the latter is my question, how can I control when the user doesn't click an object? My if statement right now only checks when the user actually clicks an object.
I'm aware that I need to move the verify function to my setTimout call for each object. But I'm not sure what to look for in the if statement?
function createShapes() {
var classes = [
"shape blue size200",
"shape size200 bluetriangle",
];
var id = [
"wrong",
"right",
];
var randomOrderArray = [];
for (i = 0; i < classes.length; i++) {
var randomElement = document.createElement("div");
randomElement.setAttribute("id", id[i]);
randomElement.setAttribute("class", classes[i]);
randomElement.classList.add();
randomOrderArray.push(randomElement);
}
// Calls shuffleArray
shuffleArray(randomOrderArray);
for (i = 0; i < randomOrderArray.length; i++) {
objectElement.appendChild(randomOrderArray[i]);
}
}
// Adds eventlisteners to shapes
var objects = document.querySelectorAll(".shape");
for (i = 0; i < objects.length; i++) {
objects[i].addEventListener("click", verifyShapes);
});
}
let counter = 0;
// Verifies clicked objects
function verifyShapes() {
if (this.id == "right") {
points++;
this.removeEventListener("click", verifyShapes);
counter++;
}
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>.....</title>
<body>
<div class="content" id="content"></div>
<div class="object" id="object"></div>
</body>
</html>

Related

The array won't work with the output of my pictures

I tried to show pictures with an array so I can change it per delay, kinda like a slideshow. The problem is, that only the first picture will load. when the counter of the array changes, the picture won't load.
The paths of the images are all correct
<!DOCTYPE html>`enter code here`
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<script>
var bilder = [];
var zeit = 3000;
var p = 0;
bilder[0] = "../Bilder/Bild1.jpg";
bilder[1] = "../Bilder/Bild2.jpg";
bilder[2] = "../Bilder/Bild3.jpg";
bilder[3] = "../Bilder/Bild4.jpg";
function BildAutoWeiter()
{
document.bild.src = bilder[p];
for( var i=0; i<= bilder.length; i++)
{
if(i <= bilder.length)
{
p++;
}
else
{
i = 0;
}
}
setTimeout("BildAutoWeiter()", zeit);
}
</script>
</head>
<body onload="BildAutoWeiter()">
<div>
<img name ="bild" width="100%" height="50%">
</div>
</body>
</html>
You need to use getElementsByName() to choose elements by their name=''. That returns an array of elements that use that name, so to choose a specific one, use an index [index] starting from 0. Do this instead:
document.getElementsByName('bild')[0].src = bilder[p];
That selects the first element that uses name='bild'
Also, the for statement is a bit useless. You could instead do:
function BildAutoWeiter()
{
document.bild.src = bilder[p];
p++;
setTimeout(BildAutoWeiter, zeit);
}
You don't need to put the function name in quotations and you can't have the parentheses while calling the function in setTimeout.

Re-using a variable not possible due to scoping issue. How can I fix this?

I expect to be able to use 'validBet' in a new function. The validBet is the basically the last value of the array 'betButtonsArr'. So the last clicked button will be the bet, not any of the previous. Now I need to be able to use the validBet to determine the bet placed, to calculate loss/winnings in a new function.
The problem is that I get a validBet is undefined error.
I am only using VanillaJS since I want to learn JS first before moving onto libraries.
// starter cash will be 100.
var cashTotal = 100; //Cash currently holding.
var showTotal = document.querySelector("#amount").innerHTML = cashTotal;
var bet = [5, 10, 50, 100]; //Bets you can do.
var numGenerated;
function updateDisplay() {
document.querySelector('#generated_number').innerHTML = "".split.call(numGenerated, "").join("");
}
function highLow(){
var storeNum = Math.floor(Math.random() * 11) + 0;
numGenerated = storeNum;
}
function choiceLow(){
highLow();
updateDisplay();
console.log(numGenerated);
if (numGenerated < 5){
// run function to add winnings
}
else {
// run function to subtract bet amount.
return;
}
}
function choiceHigh(){
highLow();
updateDisplay();
console.log(numGenerated);
if (numGenerated == 5 || numGenerated > 5){
// run function to add winnings.
}
else {
// run function to subtract bet amount.
return;
}
}
var betAmount = [];
function placeBet(){
var betBtn_nodelist = document.querySelectorAll('.bet_amount > button');
var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist);
//
for (var i = 0; i < betButtonsArr.length; i++) {
betButtonsArr[i].onclick = function(){ // when clicked, push value of clicked button to betAmount array for grabbing the placed bet.
betAmount.push(this.value);
console.log(betAmount);
var validBet = betAmount[betAmount.length - 1]; // when multiple bet amounts are clicked, take the last amount chosen, make that the final and valid bet amount.
console.log(validBet) //This is the real bet amount, as explained one line above.
console.log(cashTotal)
}
}
}
placeBet();
function addWinningsAmount(){
}
function subtractBetAmount(){
}
var lower = document.querySelector("#lower");
var higher = document.querySelector("#higher");
lower.addEventListener('click', choiceLow);
higher.addEventListener('click', choiceHigh);
HTML code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Betting Project</title>
<link rel="stylesheet" href="betting.css">
</head>
<body>
<div class="cash_total"><p>Your balance is: <span id="amount"></span>.</p></div>
<h1 style="text-align: center;">BET NOW</h1>
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>
<div id="generated_number"></div>
<div class="buttonHolder" style="text-align: center;">
<button id="lower">LOWER</button>
<button id="higher">HIGHER</button>
</div>
<script src="betting.js"></script>
</body>
</html>
I expect to use this and grab the value of the bet. Instead of that, I get the ReferenceError: validBet is not defined. I'm guessing this is a scoping problem, but I have no idea how to best sort this out.
function addWinningsAmount(){
console.log(validBet)
}
when declaring global objects in javascript, you need to declare it at the top. Any variable declared inside a function is limited to that function only.
or else, if the variable still needs to be declared inside the function but with global scope, use window declaration. For eg. window.validBet = betAmount[betAmount.length - 1];. Make sure the function declaring the variable is called before the function accessing the variable.
do not use 'var' while declaring global variables.

How to set a maximum amount of clicks on an order button for each item specifically? (JavaScript)

I'm trying to implement a functionality where the user can only order a set amount of times (let's take 5 times for example) before an alert shows up saying that the product he is trying to order has ran out of stock.
He can still of course, order other product that haven't been clicked on 5 times.
The problem I'm facing is that I don't know how to keep count of each order button (an anchor acting as a button) specifically.
I tried implementing that functionality and it does show an alert, but it takes count of all order buttons clicked.
This is how my functions looks:
let counter = 0; //global variable
function order_func() {
let every_product= document.querySelectorAll(".all_prods");
for (let each_prod = 0; each_prod < every_product.length; each_prod++) {
every_product[each_prod].addEventListener("click", function (e) {
if(count_stuff < 10){
add_it(e, each_prod); //e to preventDefault() and console.log "each_prod"
count_stuff++;
}else{
out_of_stock(e); //shows the alert it takes the event as argument to prevent default behavior.
}
});
}
}
add_it() is just a function that console.log()'s the product.
I'm only using vanilla JS, I don't want to use any other libraries for this :)
you can use data attribute to store temp values in page. take a look on this example using JQuery.
<!-- index.html -->
Order
<script>
$('#order-btn').click(function() {
var maxCounts = this.data('maxCounts');
var count = this.data('count');
if (count >= maxCount) {
alert('you cant order any more');
return;
}
this.data('count',count++);
// other logic .e.g Ajax call
})
</script>
you can do it using vanilla JS also:
<script>
let counter = 0; //global variable
function order_func() {
let every_product= document.querySelectorAll(".all_prods");
for (let each_prod = 0; each_prod < every_product.length; each_prod++) {
every_product[each_prod].addEventListener("click", function (e) {
var count_stuff = e.target.dataset.count; // or this.dataset.count
var max_count = e.target.dataset.maxCounts; // or this.dataset.maxCounts
if(count_stuff < max_count){
add_it(e, each_prod);
e.target.dataset.count = count_stuff++;
}else{
out_of_stock(e);
}
});
}
}
</script>

I have been makign a code with javascript that run o. while I have made it run n

I have been writing Javascript code to show a traffic light with a changing image. It uses a set array but I am new to coding and have not been told how to do this. I have written the code below but it is still not working. I can get it to run by clicking it but I need it to run without having to press the button lots of times.
It changes between images that are in the same folder as the code. I want it to work by a person only pressing the button once.
HTML:
<img id="light" src="traffitlr.jpeg">
<button type="button" onclick="changeLights()">changelights(and Start Lights)</button>
<button type="button" onclick=setinterval(change,1000)>start auto cycle</button>
Javascript:
var list = [
"traffitlg.jpg",
"traffitla.jpg",
"traffitlr.jpg",
"traffitly.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('light');
image.src=list[index];
}
var list = [
"traffitlg.jpg",
"traffitla.jpg",
"traffitlr.jpg",
"traffitly.jpg"
];
var index = 0;
var startChangeLights=function changeLights() {
console.log("change lights");
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('light');
image.src=list[index];
setTimeout(changeLights,6000);//change in 6 seconds ( 6000milliseconds)
startChangeLights=function(){console.log("already started");};//prevent user from starting multiple times
}
Use like this:
startChangeLights();//change lights
startChangeLights();//already started
//after 6 s : change Lights
I mainly use a Timeout, that changes the lights every 6 seconds. I also use an named-anonymous function, to prevent starting twice...

Confused about passing multiple images to Image() objects

I think I'm missing an obvious rule here and it would be great to get it clarified -
I'm trying to write an image preloader and I'm following the advice given on this posting:
Preloading images in Javascript? Without jQuery
I can see how it all works up until:
for(var i = 0; i < imageList.length; i++ ) {
var imageObject = new Image();
imageObject.src = imageList[i]; }
I keep thinking this would simply change/overwrite the src property at every iteration, leaving imageObject.src as the last image in the list at the end of the loop, though clearly the function is meant for using multiple images.
So I'm assuming it leaves imageObject containing an array of images but I'm not sure how it does this. What do I have wrong?
What you have will "probably" work. But, it's not the ideal way to do things because it relies on some undocumented aspects of a browser and garbage collection. See here and here for safer ways to do this. I'll try to explain what your code is doing.
When you do this line:
var imageObject = new Image();
it is creating a new DOM image object and placing a reference to that object in the variable imageObject.
When you do this line:
imageObject.src = imageList[i];
it is assigning the .src property of that new image object. This will NOT be overwriting the .src property on the previous image object.
But, because the previous image objects are not stored anywhere and no other javascript has any references to them, they are available for garbage collection by the browser and it is free to get rid of them at any time. To use this for reliable caching, you are hoping that the browser does not cancel the networking operation in progress that is loading the images and you are hoping that they still get into the browser cache so they are preloaded.
It is much safer to store the imageObject in an array as the other solutions I've pointed you to will do. This keeps them from being garbage collected so there is no risk that their image loading will be cancelled.
For example, it would be safer to do this:
var imgs = [];
for (var i = 0; i < imageList.length; i++ ) {
var imageObject = new Image();
imageObject.src = imageList[i];
imgs.push(imageObject);
}
The previous two references to other solutions to this do something similar, but package this in a function and one also has the ability to notify you when all the images have finished preloading.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var imageList = new Array("dummyImg1.jpg", "dummyImg2.jpg");
var imagePlaceholder = new Array(imageList.length);
function waitImagesLoaded() {
var allImagesLoaded = true;
for (var i = 0; i < imageList.length && allImagesLoaded; i++) {
allImagesLoaded &= imagePlaceholder[i].complete;
}
if (allImagesLoaded) {
for (var i = 0; i < imageList.length; i++) {
var imgElemIdToReplace = "img" + String(i + 1);
replaceElem(imagePlaceholder[i], document.getElementById(imgElemIdToReplace));
}
} else {
window.setTimeout(waitImagesLoaded, 500);
}
}
function replaceElem(substituteElem, elemToReplace) {
var parentNode = elemToReplace.parentNode;
parentNode.replaceChild(substituteElem, elemToReplace);
}
</script>
</head>
<body>
<img id="img1" src="" alt="">
<img id="img2" src="" alt="">
<script type = "text/javascript">
for (var i = 0; i < imageList.length; i++) {
var imageObject = new Image();
imageObject.src = imageList[i];
imagePlaceholder[i] = imageObject;
}
window.setTimeout(waitImagesLoaded, 500);
</script>
</body>
</html>

Categories

Resources