How to show only selected number of elements in array? - javascript

I developed a party-game just for fun, and can't solve this problem. So, at first I ask user "How many clothes you want to see?". I set that data to local storage, and use on other page. So my problem is: I want to show only user selected number of elements in array (I'm so sorry for my bad english, I really need your help). Here are my codes:
index.html
<div class="container">
<div class="small-container">
<p id="text">How many clothes you want to choose ?</p>
<input type="number" placeholder="1 to 6" id="count" />
</div>
<button id="btn">Start</button>
</div>
script1.js
window.onload = function() {
var btn = document.getElementById("btn");
var count = document.getElementById("count");
btn.addEventListener("click", function() {
document.location.href = "random.html";
localStorage.setItem("count", count.value);
});
};
game.html
<div class="small-container">
<p id="text">Your random clothes: </p>
<img id="img" />
</div>
script2.js
var options = [
"T-Shirt",
"Singlet",
"Underwear",
"Socks",
"Shorts",
"Shoes"
];
var btn = document.getElementById("btn");
var text = document.getElementById("text");
var img = document.getElementById("img");
btn.addEventListener("click", function() {
var count = localStorage.getItem("count");
var randomChoice = options.splice(Math.floor(Math.random() * options.length), 1);
btn.innerHTML = "Shuffle";
text.innerHTML = randomChoice;
img.setAttribute("src", `img/${randomChoice}.png`);
if (randomChoice >= options.length) {
text.innerHTML = "End of game :)";
btn.innerHTML = "Start again";
img.removeAttribute("src");
btn.addEventListener("click", function() {
// document.location.href = "intro.html";
document.location.href = "random.html";
});
}
});
};
So every time user clicks the button, clothes are changing. For example, if user was chosen 4 as count, I want to show him/her only 4 clothes, and they must see before every click just one image on their pages.

If i understood ur question correctly, your issue was that you didnt know how to stop the game once the good amount of clothes has been shown
Here is a solution
btn.addEventListener("click", function() {
var count = localStorage.getItem("count");
localStorage.setItem("count", count-1); //decreasing the value of count because one clothe is about to be shown on screen
if (count == 0) { //if count is at 0, that means game is over
text.innerHTML = "End of game :)";
btn.innerHTML = "Start again";
img.removeAttribute("src");
btn.addEventListener("click", function() {
// document.location.href = "intro.html";
document.location.href = "random.html";
});
}
else{ //we show a new cloth
var randomChoice = options.splice(Math.floor(Math.random() * options.length), 1);
btn.innerHTML = "Shuffle";
text.innerHTML = randomChoice;
img.setAttribute("src", `img/${randomChoice}.png`);
}
});
But with that code its still possible that the same cloth is picked several times.
To avoid that, while keeping the code in pure javascript, I guess you could use "hidden" inputs to store the clothes that have been shown, or other localStorage variables.

Related

Display button value in div onclick. Javascript/HTML

I have a set of buttons with different values. When I press a button I want the value of the button to be displayed in the div picked_letters, but nothing is showing. The code is divided in an html file and a javascript file.
html file looks like this:
<body>
<script src="cases.js"></script>
<div id="written_word">
</div>
<div id="list_of_letters">
</div>
<div id="picked_letters">
</div>
</body>
and the onclick in the javascript file looks like this:
for(let i = 0; i < 26; i++) {
let btn = document.createElement("button");
btn.style.background = 'silver';
btn.style.width = '15%';
btn.style.fontWeight = 'bold';
btn.style.fontSize = '135%';
btn.style.display = 'inline-block';
btn.value = case_values[i];
btn.onmouseover = function (){
btn.style.background = 'goldenrod';
}
btn.onmouseleave = function() {
btn.style.background = 'silver';
}
btn.onclick = function() {
btn.style.background = 'darkgrey';
btn.disabled = true;
btn.innerHTML = String(btn.value);
document.getElementById("picked_letters").innerHTML =
String(btn.value);
}
btn.innerHTML = String(i+1);
document.body.appendChild(btn);
}
The button changes color, becomes disabled and displays the value inside the button but it's the last line with getting the button value into a div that I am having problems with. Have looked around but haven't found a solution that solves this problem.
##Edit: The problem seems to have been fixed when I put the script import at the end of the body (and some other minor changes).
Where are you setting the value of the button?
Can you share the button code?
Does your button look like this?
<button>My Button</button>
or do you set your value like this?
<button value="my button value">My button</button>
If you have a value set - you can do this:
btn.onclick = function () {
console.log(btn.innerHTML);
btn.style.background = "darkgrey";
btn.disabled = true;
document.getElementById("picked_letters").innerHTML = btn.value;
};
If you don't have a value set - using btn.value won't return anything.
I would try adding a value to your button if you dont have one. Or if you want to call the innerhtml of the button:
<button>My button</button>
and then
btn.onclick = function () {
console.log(btn.innerHTML);
btn.style.background = "darkgrey";
btn.disabled = true;
document.getElementById("picked_letters").innerHTML = btn.innerHTML;
};
The code above is perfectly fine, the is definately being displayed in the "picked_letters" div, but the value of btn is ""(empty) so the value set to the div is also empty. To solve this issue, add value to the button by doing:-
. and the issue will be gone.
const btn = document.querySelector('#btn')
btn.onclick = function() {
btn.style.background = 'darkgrey';
btn.disabled = true;
console.log(btn.value)
btn.innerHTML = String(btn.value);
document.getElementById("picked_letters").innerHTML =
String(btn.value);
}
<body>
<div id="written_word">
</div>
<div id="list_of_letters">
</div>
<div id="picked_letters">
</div>
<button id='btn' value='5'>Tap me</button>
</body>

Vanilla Javascript : how to make a button clickable once only

I have a quiz app application that I am working on that dynamically creates 2-4 buttons for the answer. However, if you click on an answer, you can keep clicking on the same answer or keep clicking the other answers. I want the user to be able to click one of the buttons but then not be able to keep clicking. caveat though: when a user clicks one of the buttons, a new "Next" button gets created and that one does still need it's click event.
tl;dr
I need dynamically created buttons to be clickable only once but a "Next" button to still be clickable.
Code:
function renderButtons() {
var answerContainer = document.getElementById("answer-buttons");
answerContainer.innerHTML = "";
for (var i = 0; i < 4; i++) {
var button = document.createElement("button");
button.classList.add("btn");
button.setAttribute("id", "answerBtns");
button.hasAttribute("data-correct");
button.setAttribute("data-correct", questions[count].answers[i].correct);
button.onclick = btnclick;
button.textContent = questions[count].answers[i].text;
answerContainer.appendChild(button);
}
}
// if user clicks on button check if true
function btnclick(e) {
e.preventDefault();
var value = event.target.dataset.correct;
scoreBox.textContent = "Score: " + score;
if (value === "true") {
score += 5;
document.body.style.background = "green";
} else {
document.body.style.background = "red";
}
var next = document.getElementById("answer-buttons");
var nextBtn = document.createElement("button");
nextBtn.classList.add("nextBtn");
nextBtn.textContent = "Next";
next.appendChild(nextBtn);
nextBtn.onclick = nextBtnFx;
if you want to see what I'm talking about, the app can be found here:
https://andrethetallguy.github.io/Animal-Quiz/
Thanks!!!
In the handler function nextBtnFx you could disable the button with
this.disabled = "true"
that would make it unclickable after the first click
ref: https://stackoverflow.com/a/17115132/13998159
<!DOCTYPE html>
<html>
<head>
<title>Button</title>
</head>
<body>
<input type="button" id="btn01" value="OK">
<button onclick="disableElement()">Disable</button>
<button onclick="enableElement()">Enable</button>
<script>
function disableElement() {
document.getElementById("btn01").disabled = true;
}
function enableElement() {
document.getElementById("btn01").disabled = false;
}
</script>
</body>
</html>
You can use these functions to disable/enable the buttons.

Randomly generate user input

Im really new to coding, and i wanted to know if it was possible to randomly generate entries submitted by a user.
For example.
If the user was to enter 5 words,
Would they then be stored in a way that you would have a button to just click 'next' and randomly move through them.
Ive checked all around but cant seem to find anything,
Please help!!
Thanks
Your question is very abstract but the answer below details the following:
A user is able to save an infinite number of words.
A button is then able to randomly take one of these words and display it on the screen.
preview
https://jsfiddle.net/gwcq2qc9/1/
html
<input id="word"><button id="save">save</button>
<br><br>
<button id="show">show</button><br>
Random: <span id="output">...</span>
javascript
var words = [];
var input = document.getElementById('word');
var saveButton = document.getElementById('save');
var showWordButton = document.getElementById('show');
var output = document.getElementById('output');
saveButton.addEventListener('click', function () {
words.push(input.value);
input.value = '';
}, false);
showWordButton.addEventListener('click', function () {
output.innerHTML = getRandomWord();
})
function getRandomWord () {
return words[Math.floor(Math.random()*words.length)]
}

Displaying an average of two variables

I'm having trouble displaying the average number of clicks per round a user does for a challenge. When I go into the console I am able to calculate the average number, but I can't seem to figure out how to get it to display.
JFiddle:
https://jsfiddle.net/tglas/tkL4p8on/5/
My CSS:
<div>
round:<span id="rounds">1</span>
</div>
<div >
clicks:<span id="clicks">0</span>
</div>
<div>
Average:<span id="avgDisplay">0</span>
</div>
<button id="reset">
New Round
</button>
<button id="option1">
Option 1
</button>
<button id="option2">
Option 2
</button>
And JS:
var roundsDisplay = document.querySelector("#rounds");
var clicksDisplay = document.querySelector("#clicks");
var option1 = document.querySelector("#option1")
var option2 = document.querySelector("#option2");
var reset = document.querySelector("#reset")
var rounds = 1;
var clicks = 0;
var avg = clicks / rounds;
option1.addEventListener("click", function() {
clicks++;
clicksDisplay.innerHTML = clicks;
})
option2.addEventListener("click", function() {
clicks++;
clicksDisplay.innerHTML = clicks;
})
reset.addEventListener("click", function() {
rounds++;
roundsDisplay.innerHTML = rounds;
})
avgDisplay.innerHTML = avg;
I know I am probably missing something fundamental here, but I'm new to programming and would appreciate any help figuring out this concept.
You're just calculating the average one time, the first time your JS file runs. But you want to calculate the average every time you increase the counter.
Just create a function that calculates the average value every time a button is pressed and create a avgDisplay variable. (Like Olivier mentioned in the comments)
var avgDisplay = document.querySelector("#avgDisplay");
function updateAverage() {
avgDisplay.innerHTML = clicks / rounds;
}
and add it to your event callbacks after you've increased the counter
e.g.
option2.addEventListener("click", function() {
clicks++;
clicksDisplay.innerHTML = clicks;
updateAverage();
})

How to change button text over time in Javascript?

I have a button on my page. And I would like that button to change language every 2/4 seconds with Javascript. e.g. When the page loads the text of the button will be search, and after 2 or 4 seconds it will change to other languages. It doesn't need to be an infinite loop, just the most simple.
HTML:
<button id="search" name="q">search</button>`
Javascript:
var x = document.getElementById('search');
//after 2 seconds:
x.innerHTML="Suchen";
//And so on
This is the most robust and simple solution for your problem. JSFIDDLE.
Loop through a predefined language dictionary using setInterval()
var x = document.getElementById('search'),
// dictionary of all the languages
lan = ['Search', 'Suchen', 'other'],
// hold the spot in the dictionary
i = 1;
setInterval(function (){
// change the text using the dictionary
// i++ go to the next language
x.innerHTML = lan[i++];
// start over if i === dictionary length
i = lan.length === i ? 0 : i;
}, 2000);
> Demo : http://jsfiddle.net/JtHa5/
HTML
<button id="search" name="q">Search</button>`
Javascript:
setInterval(changeButtonText, 2000);
function changeButtonText()
{
var btnTxt = document.getElementById('search');
if (btnTxt.innerHTML == "Search"){
btnTxt.innerHTML = "Suchen";
}
else{
btnTxt.innerHTML = "Search";
}
}
Use setInterval.
setInterval(function() {
var btn = document.getElementById('search');
if (btn.innerHTML == "search")
btn.innerHTML = "Suchen";
else
btn.innerHTML = "search";
}, 2000);
You could also change the button to an input and use the value property instead of the innerHTML property.
Here's the Javascript:
function changeButton() {
var btn = document.getElementById('myButton');
if (btn.value == "Search")
btn.value = "Suchen";
else
btn.value = "Search";
}
setInterval(changeButton, 2000);
And the HTML
<input type="button" id="myButton" value="Search" />

Categories