How do I start this javascript code on click - javascript

EDITED: Ok, I didn't explain well. I have added a button in the HTML. When you click that, it alerts and asks for user to enter questions and answers. BUT...it doesn't push that array into the cards themselves.
I have hacked together a simple javascript flash card program. But it starts immediately on page load. How do I make it start on click of a single <button>? I've tried enclosing the entire code in a function but then the user inputs that create the array don't get passed to the flashcards -- I assume because they are separate functions. I'm probably not explaining this well. But I want the entire program to run on click of one button. I appreciate any help.
#flashcardFront {
margin-top: 100px;
margin-left: 400px;
width: 300px;
height: 50px;
background-color: black;
color: white;
font-family: arial;
font-size: 22px;
text-align: center;
padding: 50px 0;
display: block;
}
a:link {
text-decoration: none;
}
#number {
color: red;
position: relative;
left: -120px;
top: 30px;
}
<div>
<button onclick='cards();'>button</button>
<a id="flashcardFront" href="#" onclick="flashCards();"></a>
</div>
var myArray = [];
for (var i = 0; i < 2; i++) { // # of loops
myArray.push(prompt('Enter question ' + (i+1))); // push the value into the array
myArray.push(prompt('Enter answer ' + (i+1))); // push the value into the array
}
/*var myArray = [
"Q: What's my name?", 'A: Heck no.',
'Q: My age?', "A: Cool kids don't say.",
'Q: Fave rocker?', 'A: Paul Gilbert'
];*/
var myIndex = 0;
function renderQuestion(index) {
// render number if index is even
var str = myArray[index]
if (index % 2 == 0) {
str += '<br><span class="question-number">' + (index / 2 + 1) + '</span>'
}
return str
}
function flashCards() {
var flashcardFront = document.getElementById('flashcardFront');
flashcardFront.innerHTML = renderQuestion(myIndex);
myIndex = (myIndex + 1) % (myArray.length);
}
flashCards()

I think the issue here is that myIndex is a global. The first time flashcards runs, it increments the index to the length of the array, so the next time it runs (in the click handler) it's already at the end of the array. Set it to 0 at the beginning of flashcards.

At the end of the code, you call flashCard() javascript function which cause your page to load the first question immediately after user entered all prompted inputs. Remove it and your application is good to go.

var questionsAndAnswers = [];
var myIndex = 0;
function showAllQuestionsAndAnswers() {
for (var i = 0; i < questionsAndAnswers.length; i++) {
if(i % 2 == 0) {
alert("Question: " + questionsAndAnswers[i]);
}
else {
alert("Answer: " + questionsAndAnswers[i]);
}
}
}
/*var myArray = [
"Q: What's my name?", 'A: Heck no.',
'Q: My age?', "A: Cool kids don't say.",
'Q: Fave rocker?', 'A: Paul Gilbert'
];*/
function renderQuestion(index) {
// render number if index is even
var str = questionsAndAnswers[index]
if (index % 2 == 0) {
str += '<br><span class="question-number">' + (index / 2 + 1) + '</span>'
}
return str
}
function flashCards() {
for (var i = 0; i < 2; i++) { // # of flash cards
questionsAndAnswers.push(prompt('Enter question ' + (i+1))); // push the value into the array
questionsAndAnswers.push(prompt('Enter answer ' + (i+1))); // push the value into the array
}
var flashcardFront = document.getElementById('flashcardFront');
flashcardFront.innerHTML = renderQuestion(myIndex);
myIndex = (myIndex + 1) % (questionsAndAnswers.length);
}
function startGame() {
flashCards();
}
document.getElementById("start_game").onclick = function() {startGame()};
#flashcardFront {
margin-top: 100px;
margin-left: 400px;
width: 300px;
height: 50px;
background-color: black;
color: white;
font-family: arial;
font-size: 22px;
text-align: center;
padding: 50px 0;
display: block;
}
a:link {
text-decoration: none;
}
#number {
color: red;
position: relative;
left: -120px;
top: 30px;
}
<div>
<button onclick='cards();'>button</button>
<button id="start_game">
Start Game
</button>
<a id="flashcardFront" href="#" onclick="flashCards();"></a>
</div>

Related

Where is my setting and calling of a shuffle array function going wrong?

I'm able to loop a function to display 5 random images. Now I want to use the same 5 images and shuffle them, where each image appears only once (giving 5! = 120 permutations).
I've found plenty of tips on how to shuffle and display random numbers (not images), but where I think my issue is is setting and then calling functions. How do I do that?
Assumptions:
Between my <style> tags I need to define my shuffle function
My array of images can remain as it is (since it's the same ones, clearly making sure to update any changed references form the new URL)
The shuffle function gets called in the body of my page (I'm not sure about this bit)
In simple English I'm trying to achieve:
"Take the five images in the collection and put them, once only, into any order."
What happens:
Five images appear, often images are repeated.
The successful webpage has this:
</style>
<script type="text/javascript">
// place your images in this array
var random_images_array = ['Weare.jpg', 'Always.jpg', 'There.jpg', 'For.jpg', 'You.jpg'];
function getRandomImage(imgAr, path) {
path = path || '../Public/images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
</script>
</head>
<body>
And then this (which is, I assume the calling of the function)
<div>
<!-- This script segment displays an image from the array -->
<script type="text/javascript">for (i = 0; i < 5; i++) getRandomImage(random_images_array, 'images/')</script>
</div>
How can I fix this?
The following shuffles an array of image URLs, and then adds those URLs as images to the DOM, one by one.
const $ = document.querySelector.bind(document)
function shuffle(arr) {
for (let curr = arr.length - 1; curr >= 0; --curr) {
const random = ~~(Math.random() * curr)
;[arr[random], arr[curr]] = [arr[curr], arr[random]]
}
return arr
}
function render(arr) {
let html = "";
for (let el of arr) {
html += img`${el}`
}
$("#images").innerHTML = html
}
function img(_, url) {
return `<img style="background:url(${url}); background-size:cover;"/>`
}
const arr = [
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX//wCKxvRFAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUA/wA0XsCoAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/AAAZ4gk3AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg=="
]
$("button").addEventListener("click", () => render(shuffle(arr)))
render(shuffle(arr))
body {
font-family: sans-serif;
font-size: 0;
}
img {
display: inline-block;
width: 170px;
height: 60px;
box-shadow: 0 0 0 2px white inset;
padding: 0;
margin: 0;
}
button:focus { outline: none }
button {
font-size: 1rem;
border: none;
background: rgb(0, 200, 200);
border-radius: 5px;
cursor: pointer;
line-height: 40px;
height: 40px;
width: 340px;
padding: 0;
margin: 0;
color: white;
-webkit-user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
box-shadow: 0 0 0 2px white inset;
}
#images {
box-shadow: 0 0 0 2px silver inset;
width:340px;
height:120px;
}
<button>Shuffle!</button>
<section id="images"></section>
A kind commenter who deleted their answer gave me the following:
var random_images_array = ['Weare.jpg', 'Always.jpg', 'There.jpg', 'For.jpg', 'You.jpg'];
function shuffleArray(arr) {
for (var i = arr.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Shuffle images here
shuffleArray(random_images_array);
function getRandomImage(imgAr, path) {
path = path || '../Public/images/'; // default path here
for (var i = 0; i < imgAr.length; i++) {
var img = imgAr[i];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}
}
getRandomImage(random_images_array, 'images/')
And it worked! Thank you, mystery helper!

Add scores grid game JavaScript

I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)

limit a random number generator to only output 20 of 50 numbers

I need some help or advice I am trying to limit the random number to only generate 20 out of the 50 numbers and this activated when a button is pressed/clicked sometimes i get duplicates too which i would to stop happening
function lottoNumbers()
{
var lottoNums = [];
for(var i=0; i <1 ; i++)
{
var temp = Math.floor(Math.random() *50);
if(lottoNums.indexOf(temp) == -1)
{
lottoNums.push(temp);
document.getElementById('circle'+i).innerHTML = lottoNums[i];
}
else
{
i--;
}
}
}
Rather than using a for loop - use a while loop (ie - while length < 20) and as you are doing - only push the numbers into it if they are not already there.
For demo purposes- i am building a list dynamically and then styling the li's to give a rounded shape with border-radius;
lottoNumbers();
function lottoNumbers() {
var lottoNums = [];
var lottoNumStr = '';
while(lottoNums.length <20) {
var temp = Math.floor(Math.random() *50);
if(lottoNums.indexOf(temp) == -1) {
lottoNums.push(temp);
lottoNumStr += '<li>' + temp + '</li>';
}
}
document.getElementById('lottoNumList').innerHTML = lottoNumStr;
}
#lottoNumList {
list-style: none;
}
#lottoNumList li {
border: solid 1px #d4d4d4;
border-radius: 50%;
display: inline-block;
margin: 5px;
padding: 4px;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
}
<h1>Lotto Numbers</h1>
<ul id ="lottoNumList"></ul>

Why would I get different results from a function due to the position of number 1 in an array?

I have a few problems that are stopping me from proceeding on my blackjack 21 game. First when I open the site in a browser my aceCard function is invoked which is only supposed to be called if you deal a 1 (an ace card). Below I have written some problems I noticed with my aceCard function.
When You get number 1 in the userArray then you will need to call aceCard(); in the console. Or at least I haven't got this to call automatically.
1.when number 1 is in position 0 in array javascript don't recognize the 1.
2.when number 1 is in position 1 in array aceCard function will work and change value to 1 to 11
3.when number 1 is in position 2 in array it see's value 1 in the array, but it won't change value 1 to 11. if array position 0 = 1 then it won't see position 2 in the array.
Any help would be great, I have no idea why this works differently depending where number 1 is positioned in the userArray.
var userArray = [];
var computerArray = [];
var a = userArray.indexOf(1);
function random_number() {
var randNum = Math.floor(Math.random() * 10 + 1);
return randNum;
}
document.getElementById('dealButton').onclick = function() {
userArray.push(random_number(), random_number());
computerDeal();
computerDeal();
calcTotal(userArray);
showMe(calcComputerTotal(userArray));
//cardMaker ();
//cardMaker ();
//inputMyCardValue ();
//inputMyCardValue ();
cardMaker(random_number());
cardMaker(random_number());
//inputMyCardValueComputer ();
//inputMyCardValueComputer ();
return userArray;
}
document.getElementById('hitButton').onclick = function() {
userArray.push(random_number());
//computerHit();
calcTotal(userArray);
showMe(calcComputerTotal(userArray));
cardMaker(random_number());
//inputMyCardValue ();
//cardMakerComputer ();
//inputMyCardValueComputer ();
return userArray;
}
if (userArray.indexOf(1)) {
aceCard();
}
function aceCard() {
if (userArray.indexOf(1)) {
var numberDesired = parseInt(prompt('You got an Ace card! Do you want it to equal 1 or 11?'));
if (numberDesired === 11) {
var a = userArray.indexOf(1);
userArray[a] = 11;
inputMyCardValue();
calcTotal(userArray);
};
};
}
function stay() {
//have computer try to get closest to 21 as posible
}
/*function cardMaker (number) {
var id = 'card' + ($('#cardTable').children().length + 1);
$("#cardTable").append('<div id="' + id + '" class="cardLook">' + number + '</div>');
}*/
function cardMakerComputer() {
var id = 'cardComputer' + ($('#computerCardValues').children().length + 1);
$("#cardTable").append('<div id="' + id + '" class="cardLook"></div>');
}
function inputMyCardValue() {
card1.innerHTML = userArray[0];
card2.innerHTML = userArray[1];
card3.innerHTML = userArray[2];
card4.innerHTML = userArray[3];
card5.innerHTML = userArray[4];
card6.innerHTML = userArray[5];
}
function cardMaker() {
var id = 'card' + ($('#cardTable').children().length + 1);
$("#cardTable").append('<div id="' + id + '" class="cardLook">' + userArray[$('#cardTable').children().length] + '</div>');
}
inputMyCardValue()
inputMyCardValue()
function inputMyCardValueComputer() {
card10.innerHTML = computerArray[0];
card20.innerHTML = computerArray[1];
card30.innerHTML = computerArray[2];
card40.innerHTML = computerArray[3];
card50.innerHTML = computerArray[4];
card60.innerHTML = computerArray[5];
aceCard();
}
function calcTotal(userArray) {
var total = 0;
for (var i = 0; i < userArray.length; i++) {
total += userArray[i];
}
}
function calcComputerTotal(computerArray) {
var total = 0;
for (var i = 0; i < computerArray.length; i++) {
total += computerArray[i];
}
return total;
}
function showMe(VAL) {
var total = calcComputerTotal(userArray);
total = document.getElementById('out2');
parent = total;
parent.innerHTML = VAL;
}
//Cumputer logic
function computerDeal() {
computerArray.push(random_number(), random_number());
}
/*function computerHit () {
if (calcComputerTotal(computerArray) <= 17) {
computerArray.push(random_number());
}
}*/
//when 1 is in position 0 in array javascript don't reconise the 1.
//when 1 is in position 1 in array aceCard function will work and change value to 1 to 11
//when 1 is in position 2 in array it see's value 1 in the array, but won't change value 1 to 11. if array position 0 = 1 then it won't see position 2 in the array.
body {
background-color: lightgrey;
}
#mainContainer {
margin: 0 auto;
padding: 15px;
}
#cardTable {
height: 240px;
width: 95%;
background-color: green;
border-radius: 5px;
margin: 15px 0 15px 0;
}
#computerCardValues {
height: 240px;
width: 95%;
background-color: green;
border-radius: 5px;
margin: 15px 0 15px 0;
}
#out2 {
margin-bottom: 5px;
}
.cardLook {
border: 1px solid black;
width: 120px;
height: 190px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,
#card2,
#card3,
#card4,
#card5 {
transform: rotate(180deg);
transform: rotate(0deg);
}
#cardComputer10,
#cardComputer20,
#cardComputer30,
#cardComputer40,
#cardComputer50 {
transform: rotate(180deg);
transform: rotate(0deg);
}
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<div id="mainContainer">
<div id="wrapper">
<div id="out2">My total</div>
<button id="dealButton">Deal</button>
<button id="hitButton">Hit</button>
<button id="stayButton">Stay</button>
<div id="cardTable"></div>
</div>
<div id="computerWrapper">
<div id="computerTotal">Computer Total</div>
<div id="computerCardValues"></div>
</div>
</div>
Heading
You're not using indexOf correctly to test whether an element is in an array. It returns the index if the element is in the array, or -1 if it's not in the array. You can't use it as a boolean, because -1 is truthy -- the only falsey value it returns is when the element is in the first array element, because then it returns the index 0.
So if (userArray.indexof(1)) should be if (userArray.indexOf(1) != -1).
There's also no point in putting
if (userArray.indexOf(1)) {
aceCard();
}
in the top-level of the script. Nothing gets put into userArray until the user starts dealing cards. So you should only do that test in the code that runs when dealing a card.

Javascript for-loop to control button click states

I'm new to JavaScript but moving over from ActionScript, so I'm using a lot of AS3 logic and not sure what's possible and not.
I have a series of 5 dots for an image slider nav. The dots are just CSS styled dots, so I'm trying to make it so I can control the colors using element.style.backgroundColor.
Here's my script:
function btnFeatured(thisBtn) {
btnFeatured_reset();
for (i = 1; i <= 5; i++) {
if (thisBtn === document.getElementById("dotFeat" + i)) {
document.getElementById("dotFeat" + i).style.backgroundColor = "#ffae00";
}
}
}
function btnFeatured_reset() {
for (i = 1; i <= 5; i++) {
document.getElementById("dotFeat" + i).style.backgroundColor = "#969696";
}
}
Seems to work just fine, but when I click the dot, it turns orange (ffae00) and then immediately turns back to gray (969696).
And just in case, here's the style I'm using for the dots:
#featured-nav a {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 8px;
background-color: #969696;
border-bottom: none;
margin: 0 14px;
}
#featured-nav a:hover {
background-color: #ffae00;
border-bottom: none;
}
And my html:
Change the HTML to
test
test
test
test
test
and the JS:
function btnFeatured(thisBtn) {
for (i = 1; i <= 5; i++) {
var state = parseInt(thisBtn.id.slice(-1),10) == i,
elem = document.getElementById("dotFeat" + i);
elem.style.backgroundColor = (state ? "#ffae00" : "#969696");
}
return false;
}
FIDDLE
Even better would be to not use inline JS, but proper event handlers.

Categories

Resources