Taking a specific action on reaching a number - javascript

I'm learning JavaScript, and decided to try out a simple guessing game thing. The code I have at the moment:
The HTML:
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="guessing_game.css">
</head>
<body>
<h1>Welcome to the guessing game</h1>
<p>You have to guess the number within 5 attempts, so good luck!</p>
<p>Enter a number:</p>
<input type="text" id="number" placeholder="Enter number"></br>
<input type="submit" id="submit" value="Guess!"></br>
<aside>
<div id="counter">
<p>Remaining Guesses</p>
</div>
<p id="remaining"></p>
</aside>
<div id="result"></div>
<script type="text/javascript" src="guessing_game.js"></script>
</body>
</html>
The JS:
var guesses = 5;
function guess() {
var elGuess = document.getElementById("remaining");
var elResult = document.getElementById("result");
/* if(guesses === 0) {
elResult.innerHTML = "<p>Sorry, you ran out of guesses! Better
luck next time.</p>";
return;
}*/
if(guesses > 0) {
guesses--;
elGuess.textContent = guesses;
//random number
var secret = Math.floor(Math.random() * 10 + 1);
var elUserGuess = document.getElementById("number");
var userGuess = parseInt(elUserGuess.value);
if(userGuess == secret) {
elResult.textContent = "Congrats! You did it";
}
else {
elResult.textContent = "Sorry, please try again.";
}
}
else {
elResult.textContent = "Sorry, you ran out of guesses.";
}
}
var elSubmit = document.getElementById("submit");
elSubmit.addEventListener("click", guess, false);
and the CSS:
body {
font-family: 'Roboto', sans-serif;
}
aside {
position: relative;
top: -150px;
width: 300px;
height: 600px;
float: right;
border-left: 2px solid gray;
}
#counter p{
position: absolute;
top: 120px;
width: 140px;
left: 60px;
border-top: 2px solid brown;
text-align: center;
border-bottom: 2px solid brown;
padding: 5px;
}
#remaining {
font-size: 220%;
text-align: center;
font-family: Arial, Verdana, serif;
position: absolute;
top: 170px;
border-bottom: 1px solid green;
padding: 2px;
left: 130px;
color: #ff2400;
}
#result {
font-family: 'Open Sans', sans-serif;
text-align: center;
font-size: 1.2em;
letter-spacing: 0.9em;
color: gray;
}
What I was looking to do was - as soon as the number of guesses reach 0, the result should display that you're out of guesses. I've managed to validate the guesses counting down to 0 (not going to negative). I tried using an if statement which would check if the guesses were out, then set the result accordingly and return. But apparently, as soon as return is reached, the control exits the method. I didn't know this would happen even inside an if that's never reached.
Either way, how do I modify the code such that the result is set as soon as the guesses left hit zero?

Remember that your variable guesses might not be what is displaying on the remaining element, you should decrement the variable before your condition.
var guesses = 5;
function guess() {
var elGuess = document.getElementById("remaining");
var elResult = document.getElementById("result");
if (guesses===0){
return;
}
guesses--;
elGuess.textContent = guesses;
if(guesses > 0) {
var secret = Math.floor(Math.random() * 10 + 1);
var elUserGuess = document.getElementById("number");
var userGuess = parseInt(elUserGuess.value);
if(userGuess == secret) {
elResult.textContent = "Congrats! You did it";
}
else {
elResult.textContent = "Sorry, please try again.";
}
}
else {
elResult.textContent = "Sorry, you ran out of guesses.";
}
}
var elSubmit = document.getElementById("submit");
elSubmit.addEventListener("click", guess, false);

Since you're decrementing your guesses counter inside that if statement, you need to move your check for guesses === 0 inside of that same block somewhere below guesses--;
if (guesses > 0) {
guesses--;
elGuess.textContent = guesses;
//random number
var secret = Math.floor(Math.random() * 10 + 1);
var elUserGuess = document.getElementById("number");
var userGuess = parseInt(elUserGuess.value);
if (userGuess == secret) {
elResult.textContent = "Congrats! You did it";
}
if (guesses === 0) {
elResult.textContent = "Sorry, you ran out of guesses."
} else {
elResult.textContent = "Sorry, please try again.";
}
}
Also, next time you post a question like this consider also linking to a free online sandbox like CodePen or JSBin. That way people can edit your code without having to copy/paste.
Here's the CodePen I made for your question:
http://codepen.io/ultralame/pen/OyWbeW.js

Related

Background is not changing accordingly in html

I am remaking Wordle for a fun project to get my brain going. I have run into an issue though where squares are getting their background color changed when they are not supposed to.
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="l1" class="letterBox"></div>
<div id="l2" class="letterBox"></div>
<div id="l3" class="letterBox"></div>
<div id="l4" class="letterBox"></div>
<div id="l5" class="letterBox"></div>
<script src="script.js"></script>
</body>
</html>
js:
var letter = 0
var id
const word = ["h","e","l","l","o"]
var guess = []
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
var key = event.key
letter+=1
id = "l".concat(letter)
document.getElementById(id).innerHTML = key
guess.push(key)
event.preventDefault();
if(letter == 5){
for(i in word){
b=parseInt(i)+1-0
letter = word[i]
for(x in guess){
gulet = guess[x]
if(gulet==letter){
id = "l"+b
document.getElementById(id).style.background = "yellow"
}
}
}
}
}, true);
css:
html, body {
width: 100%;
height: 100%;
}
#element1 {display:inline-block;margin-right:10px;}
.letterBox {
display: inline-block;
text-align: center;
font-size: 40px;
height: 50px;
width: 50px;
background-color: #ffffff;
border: 2px solid black;
border-radius: 7px;
var letter = 0
var id
const word = ["h","e","l","l","o"]
var guess = []
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
var key = event.key
letter+=1
id = "l".concat(letter)
document.getElementById(id).innerHTML = key
guess.push(key)
event.preventDefault();
if(letter == 5){
for(i in word){
b=parseInt(i)+1-0
letter = word[i]
for(x in guess){
gulet = guess[x]
if(gulet==letter){
id = "l"+b
document.getElementById(id).style.background = "yellow"
}
}
}
}
}, true);
html, body {
width: 100%;
height: 100%;
}
#element1 {display:inline-block;margin-right:10px;}
.letterBox {
display: inline-block;
text-align: center;
font-size: 40px;
height: 50px;
width: 50px;
background-color: #ffffff;
border: 2px solid black;
border-radius: 7px;
<div id="l1" class="letterBox"></div>
<div id="l2" class="letterBox"></div>
<div id="l3" class="letterBox"></div>
<div id="l4" class="letterBox"></div>
<div id="l5" class="letterBox"></div>
The constant 'word' is what the letters are being compared to.
Someone removed this part so I am adding it back. An example of a word that breaks it is 'halaa' and 'haala'
I researched this problem and I have not found anyone with this same problem, so I do not know where to even start.
There are quite some mistakes in your code, I'll try to address them one by one:
Watch out ids with leading numbers
No need for the letter variable, we can use guess.length for the same result
id = "l".concat(letter) can just ben 'l' + n' (but not needed)
b=parseInt(i)+1-0 can be: parseInt(i) + 1, since the - 0 doesn't do anything
if(gulet==letter){ compares an char vs a int, won't work as expected
Fixing the above, simplifying the code, gives us something like:
const word = ["h","e","l","l","o"]
var guess = []
window.addEventListener("keydown", (event) => {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
event.preventDefault();
var key = event.key
var id = "l" + (guess.length + 1);
document.getElementById(id).innerHTML = key
guess.push(key)
if (guess.length == 5){
for (let i in guess){
if (guess[i] == word[i]){
id = 'l' + (+i + 1)
document.getElementById(id).style.background = "yellow" ;
}
}
}
}, true);
html, body { width: 100%; height: 100%; }
.letterBox { display: inline-block; text-align: center; font-size: 40px; height: 50px; width: 50px; background-color: #ffffff; border: 2px solid black; border-radius: 7px; }
#element1 {display:inline-block;margin-right:10px;}
<div id="l1" class="letterBox"></div>
<div id="l2" class="letterBox"></div>
<div id="l3" class="letterBox"></div>
<div id="l4" class="letterBox"></div>
<div id="l5" class="letterBox"></div>
I changed this code snippet for you & I hope it works
if(letter === 5){
let idx = 0;
for(let i in word){
if (word[i] === guess[i]) {
document.getElementById(`l${idx}`).style.background = "yellow";
}
idx++;
}
}

Javascript file not working when linked to Html File

I am beginner in Js ,I tried this code by some tutorials .It is not working and I don't know what and where problem is?
When embedding JavaScript in an HTML document, where is the proper place to put the tags and included JavaScript? I seem to recall that you are not supposed to place these in the section, but placing at the beginning of the section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the section as a logical place for tags.
var questions = [
'Whats your name ?',
'Where are you from?',
'What\'s your age?',
'What profile you are working on?',
'It was nice talking you :)'
];
var num = 0;
var inputBox = document.querySelector("#ans"); //
var output = document.querySelector("#result"); //
output.innerHTML = questions[num];
function showResponse() {
var input = inputBox.value;
if (inputBox.value == "") {
} else {
if (num == 0) {
output.innerHTML = `Hii ${input}`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
} else if (num == 1) {
output.innerHTML = `${input} must be a good place`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
} else if (num == 2) {
output.innerHTML = `So you are ${2017 - input} born`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
} else if (num == 3) {
output.innerHTML = `Awesome ${input}`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
}
}
}
function changeQuestion() {
inputBox.setAttribute("placeholder", "Enter your response");
output.innerHTML = questions[num];
if (num == 4) {
inputBox.style.display = "none";
}
}
$(document).on('keypress', function(e) {
if (e.which == 13) {
showResponse();
}
})
$("#ans").focus();
this is Css code
#import url(https://fonts.googleapis.com/css?family=Open+Sans:400,600);
body {
background: #50514F;
color: #fff;
font-family: 'Open Sans', sans-serif;
margin: 0;
padding: 0;
}
h1 {
font-size: 40px;
font-weight: 600;
border: 3px solid #fff;
padding: 10px 20px;
margin-bottom: 40px;
}
.flex {
display: flex;
justify-content: center;
flex-flow: column;
align-items: center;
height: 100vh;
}
#result {
font-size: 36px;
color: #fff;
}
#ans {
color: #fff;
padding: 20px;
font-size: 26px;
background: transparent;
border: 0;
}
#ans:focus {
outline: 0;
outline-offset: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Chatbot</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="1.css">
</head>
<div class="flex">
<div>
<h1>Assitant</h1>
</div>
<div id="result">
</div>
<div class="input">
<input type="text" id="ans" placeholder="Enter your response" required/>
<script type="text/javascript" src="1.js" async></script>
</div>
</div>
</html>
You have errors in the layout and you are using javascript code examples from a library jquery that you haven't included. Also your HTML file itself was incorrect and missing body definitions.
I would recommend you have a look at w3 schools and their tutorials: https://www.w3schools.com/html/html_intro.asp
Good practice is to look at online resources first before posting here.
This is your code with those issues corrected (changes the names of the script and css files to work with this tool). You also have formatting and spelling errors that you need to look at.
var questions = [
'Whats your name ?',
'Where are you from?',
'What\'s your age?',
'What profile you are working on?',
'It was nice talking you :)'
];
var num = 0;
var inputBox = document.querySelector("#ans"); //
var output = document.querySelector("#result"); //
output.innerHTML = questions[num];
function showResponse() {
var input = inputBox.value;
if (inputBox.value == "") {
} else {
if (num == 0) {
output.innerHTML = `Hii ${input}`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
} else if (num == 1) {
output.innerHTML = `${input} must be a good place`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
} else if (num == 2) {
output.innerHTML = `So you are ${2017 - input} born`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
} else if (num == 3) {
output.innerHTML = `Awesome ${input}`;
inputBox.value = "";
inputBox.setAttribute("placeholder", "Wait for 2 secs");
++num;
setTimeout(changeQuestion, 2000);
}
}
}
function changeQuestion() {
inputBox.setAttribute("placeholder", "Enter your response");
output.innerHTML = questions[num];
if (num == 4) {
inputBox.style.display = "none";
}
}
// this is jquery syntax and won't work
// $(document).on('keypress', function(e) {
// if (e.which == 13) {
// showResponse();
// }
//})
document.addEventListener('keypress', function(e) {
if (e.which == 13) {
showResponse();
}
})
// this is jquery syntax and won't work
//$("#ans").focus();
document.querySelector("#ans").focus();
#import url(https://fonts.googleapis.com/css?family=Open+Sans:400,600);
body {
background: #50514F;
color: #fff;
font-family: 'Open Sans', sans-serif;
margin: 0;
padding: 0;
}
h1 {
font-size: 40px;
font-weight: 600;
border: 3px solid #fff;
padding: 10px 20px;
margin-bottom: 40px;
}
.flex {
display: flex;
justify-content: center;
flex-flow: column;
align-items: center;
height: 100vh;
}
#result {
font-size: 36px;
color: #fff;
}
#ans {
color: #fff;
padding: 20px;
font-size: 26px;
background: transparent;
border: 0;
}
#ans:focus {
outline: 0;
outline-offset: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Chatbot</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js" async></script>
</head>
<body>
<div class="flex">
<div>
<h1>Assitant</h1>
</div>
<div id="result">
</div>
<div class="input">
<input type="text" id="ans" placeholder="Enter your response" required/>
</div>
</div>
</body>
</html>

Why do I have to click button twice before event fires?

A simple multiple choice quiz with one problem I can't solve. At first When I clicked the 'next question' button the next question and answers didn't show only when clicked a second time the next question and answers showed.
When I placed runningQuestion++ above questions[runningQuestion].displayAnswers()
like I did in the nextQuestion function the initial problem is solved but reappears after the last question when you are asked to try again. Only now when you click 'try again' now ofcourse it skips the first question.
class Question {
constructor(question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
}
displayAnswers() {
document.querySelector('.question').innerHTML = `<div class="q1">${this.question}</div>`
let i = 0
let answers = this.answers
for (let el of answers) {
let html = `<div class="name" id=${i}>${el}</div>`
document.querySelector('.answers').insertAdjacentHTML('beforeend', html)
i++
}
}
}
const q1 = new Question('What\'s the capitol of Rwanda?', ['A: Dodoma', 'B: Acra', 'C: Kigali'], 2);
const q2 = new Question('What\'s is the square root of 0?', ["A: Not possible", 'B: 0', 'C: 1'], 1);
const q3 = new Question('Who was Rome\'s first emperor?', ['A: Tiberius', 'B: Augustus', 'C: Marcus Aurelius'], 1);
const questions = [q1, q2, q3];
let runningQuestion;
let gamePlaying;
init()
document.querySelector('.button1').addEventListener('click', nextQuestion)
function nextQuestion(e) {
console.log(e.target)
if (gamePlaying === true && runningQuestion <= questions.length - 1) {
clearAnswers()
document.querySelector('.button1').textContent = 'Next Question'
runningQuestion++
questions[runningQuestion].displayAnswers()
}
if (runningQuestion >= questions.length - 1) {
document.querySelector('.button1').textContent = 'Try again!'
runningQuestion = 0
}
}
function clearAnswers() {
document.querySelectorAll('.name').forEach(el => {
el.remove()
})
}
document.querySelector('.button2').addEventListener('click', resetGame)
function resetGame() {
document.querySelector('.button1').textContent = 'Next Question'
clearAnswers()
runningQuestion = 0
questions[runningQuestion].displayAnswers()
}
function init() {
gamePlaying = true;
runningQuestion = 0;
questions[runningQuestion].displayAnswers()
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.container {
display: flex;
width: 400px;
height: auto;
margin: 100px auto;
align-items: center;
flex-direction: column;
}
.question {
margin-top: 40px;
color: rgb(102, 0, 0);
font-size: 1.4rem;
}
.answers {
display: flex;
flex-direction: column;
margin-top: 10px;
height: 100px;
margin-bottom: 15px;
}
.name {
margin-top: 20px;
cursor: pointer;
color: rgb(102, 0, 0);
font-size: 1.2rem;
}
.button1 {
margin-top: 50px;
border-style: none;
width: 350px;
height: 50px;
font-size: 1.4rem;
}
ul>li {
list-style-type: none;
margin-top: 10px;
font-size: 1.2rem;
color: rgb(102, 0, 0);
height: 30px;
cursor: pointer;
display: block;
}
.button2 {
margin-top: 20px;
border-style: none;
width: 350px;
height: 50px;
font-size: 1.4rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Quiz</title>
</head>
<body>
<div class="container">
<div class="question"></div>
<div class="answers"></div>
<button type="button" class="button1">Next Question</button>
<button type="button" class="button2">Reset</button>
</div>
<script src="app.js"></script>
</body>
</html>
The problem with the current version is that you reset runningQuestion to 0, and when clicking on the button, you execute nextQuestion, which, as the name implies, goes to the next question (runningQuestion++).
I see 2 ways of solving this. Either the "easy" way, by resetting runningQuestion to -1 so that it goes to 0:
class Question{constructor(e,s,t){this.question=e,this.answers=s,this.correct=t}displayAnswers(){document.querySelector(".question").innerHTML=`<div class="q1">${this.question}</div>`;let e=0,s=this.answers;for(let t of s){let s=`<div class="name" id=${e}>${t}</div>`;document.querySelector(".answers").insertAdjacentHTML("beforeend",s),e++}}}const q1=new Question("What's the capitol of Rwanda?",["A: Dodoma","B: Acra","C: Kigali"],2),q2=new Question("What's is the square root of 0?",["A: Not possible","B: 0","C: 1"],1),q3=new Question("Who was Rome's first emperor?",["A: Tiberius","B: Augustus","C: Marcus Aurelius"],1),questions=[q1,q2,q3];let runningQuestion,gamePlaying;init(),document.querySelector(".button1").addEventListener("click",nextQuestion);
/* Nothing changed above */
function nextQuestion(e) {
runningQuestion++; // <---------------------------------------------------------
if (gamePlaying === true && runningQuestion <= questions.length - 1) {
clearAnswers();
document.querySelector('.button1').textContent = 'Next Question';
questions[runningQuestion].displayAnswers();
}
if (runningQuestion >= questions.length - 1) {
document.querySelector('.button1').textContent = 'Try again!';
runningQuestion = -1; // <-----------------------------------------------------
}
}
/* Nothing changed below */
function clearAnswers(){document.querySelectorAll(".name").forEach(e=>{e.remove()})}function resetGame(){document.querySelector(".button1").textContent="Next Question",clearAnswers(),runningQuestion=0,questions[runningQuestion].displayAnswers()}function init(){gamePlaying=!0,runningQuestion=0,questions[runningQuestion].displayAnswers()}document.querySelector(".button2").addEventListener("click",resetGame);
/* Same CSS as yours */ *{box-sizing:border-box;margin:0;padding:0}.container{display:flex;width:400px;height:auto;margin:100px auto;align-items:center;flex-direction:column}.question{margin-top:40px;color:#600;font-size:1.4rem}.answers{display:flex;flex-direction:column;margin-top:10px;height:100px;margin-bottom:15px}.name{margin-top:20px;cursor:pointer;color:#600;font-size:1.2rem}.button1{margin-top:50px;border-style:none;width:350px;height:50px;font-size:1.4rem}ul>li{list-style-type:none;margin-top:10px;font-size:1.2rem;color:#600;height:30px;cursor:pointer;display:block}.button2{margin-top:20px;border-style:none;width:350px;height:50px;font-size:1.4rem}
<!-- Same HTML as yours --> <div class="container"> <div class="question"></div><div class="answers"></div><button type="button" class="button1">Next Question</button> <button type="button" class="button2">Reset</button></div>
or another way, which I find cleaner. A problem you can run into with your current code, is that if you have other things to keep track of, like a score, for example, you might forget to reset them as well, inside your nextQuestion function. And if you add other stuff, you'll need to reset them in multiple places in your code.
What I would do is simply reuse the resetGame function to reset everything:
class Question{constructor(e,s,t){this.question=e,this.answers=s,this.correct=t}displayAnswers(){document.querySelector(".question").innerHTML=`<div class="q1">${this.question}</div>`;let e=0,s=this.answers;for(let t of s){let s=`<div class="name" id=${e}>${t}</div>`;document.querySelector(".answers").insertAdjacentHTML("beforeend",s),e++}}}const q1=new Question("What's the capitol of Rwanda?",["A: Dodoma","B: Acra","C: Kigali"],2),q2=new Question("What's is the square root of 0?",["A: Not possible","B: 0","C: 1"],1),q3=new Question("Who was Rome's first emperor?",["A: Tiberius","B: Augustus","C: Marcus Aurelius"],1),questions=[q1,q2,q3];let runningQuestion,gamePlaying;
/* Nothing changed above */
const btn1 = document.querySelector('.button1');
init();
btn1.addEventListener("click", onButtonClick);
function isLastQuestion() { return runningQuestion >= questions.length - 1; }
function onButtonClick() {
if (gamePlaying === true && !isLastQuestion()) {
runningQuestion++;
displayQuestion();
} else {
resetGame();
}
}
function displayQuestion() {
clearAnswers();
btn1.textContent = isLastQuestion() ? 'Try again' : 'Next Question';
questions[runningQuestion].displayAnswers();
}
/* Nothing changed below */
function clearAnswers(){document.querySelectorAll(".name").forEach(e=>{e.remove()})}function resetGame(){document.querySelector(".button1").textContent="Next Question",clearAnswers(),runningQuestion=0,questions[runningQuestion].displayAnswers()}function init(){gamePlaying=!0,runningQuestion=0,questions[runningQuestion].displayAnswers()}document.querySelector(".button2").addEventListener("click",resetGame);function init(){gamePlaying=true;runningQuestion = 0;questions[runningQuestion].displayAnswers()}
/* Same CSS as yours */ *{box-sizing:border-box;margin:0;padding:0}.container{display:flex;width:400px;height:auto;margin:100px auto;align-items:center;flex-direction:column}.question{margin-top:40px;color:#600;font-size:1.4rem}.answers{display:flex;flex-direction:column;margin-top:10px;height:100px;margin-bottom:15px}.name{margin-top:20px;cursor:pointer;color:#600;font-size:1.2rem}.button1{margin-top:50px;border-style:none;width:350px;height:50px;font-size:1.4rem}ul>li{list-style-type:none;margin-top:10px;font-size:1.2rem;color:#600;height:30px;cursor:pointer;display:block}.button2{margin-top:20px;border-style:none;width:350px;height:50px;font-size:1.4rem}
<!-- Same HTML as yours --> <div class="container"> <div class="question"></div><div class="answers"></div><button type="button" class="button1">Next Question</button> <button type="button" class="button2">Reset</button></div>

Animations not playing on load or on click in Javascript

Working on a tip calculator with an animation on an h1 tag and a slideDown and slideUp on click on the h2 tags. Problem is, none of the animations are playing and the click event isn't working either.
Here is the HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tip Calculator</title>
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="stylesheet" href="midtermcss.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script src="animationJS.js"></script>
</head>
<body>
<section id="faqs">
<h1>Tip facts</h1>
<h2>Things to know before you tip</h2>
<div>
<p>Tips Account for 44 Billion dollars of the Food Industry</p>
<p>7 States require servers to be paid minimum wage like everyone else</p>
<ul>
<li>Minnessota</li>
<li>Montana</li>
<li>Washington</li>
<li>Oregon</li>
<li>California</li>
<li>Nevada</li>
<li>Alaska</li>
</ul>
<p>Current Federal minimum tipped wage is $2.13 per hour can you live on that?</p>
<p>Charging with Credit/Debit cards tends to reduce the average tip</p>
</div>
</section>
<section id="js">
<h1 id="heading">Tip Calculator</h1>
<label for="billAmount">Total Amount Of Bill:</label>
<input type="text" id="billAmount"><br>
<label for="percentTip">Percent To Tip:</label>
<input type="text" id="percentTip"><br>
<label for="amountPeople">How Many People?:</label>
<input type="text" id="amountPeople"><br>
<label for="totalTip">Tip Total:</label>
<input type="text" id="totalTip"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</section>
</body>
</html>
Here is the JS file.
$(document).ready(function() {
// runs when an h2 heading is clicked
$("#faqs h2").toggle(
function() {
$(this).toggleClass("minus");
$(this).next().slideDown(1000, "easeOutBounce");
},
function() {
$(this).toggleClass("minus");
$(this).next().slideUp(1000, "easeInBounce");
}
);
$("#faqs h1").animate({
fontSize: "400%",
opacity: 1,
left: "+=375"
}, 1000, "easeInExpo")
.animate({
fontSize: "175%",
left: "-=200"
}, 1000, "easeOutExpo");
$("#faqs h1").click(function() {
$(this).animate({
fontSize: "400%",
opacity: 1,
left: "+=375"
}, 2000, "easeInExpo")
.animate({
fontSize: "175%",
left: 0
}, 1000, "easeOutExpo");
});
});
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var billAmount = parseFloat($("billAmount").value);
var percentTip = parseFloat($("percentTip").value);
var amountPeople = parseInt($("amountPeople").value);
if (isNaN(billAmount) || billAmount <= 0) {
alert("Your bill can't be 0 or less.");
} else if (isNaN(percentTip) || percentTip <= 0) {
alert("The percentage should be a whole number.");
} else if (isNaN(amountPeople) || amountPeople <= 0) {
alert("You are 1 person never count yourself as less.");
} else {
var total = billAmount * (percentTip / 100) / amountPeople;
$("totalTip").value = total.toFixed(2);
}
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("billAmount").focus();
}
Last but not least the CSS file since the open and minus classes are listed in there
* {
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 500px;
border: 3px solid blue;
}
section {
padding: 0 1em .5em;
}
section.js {
padding: 0 1em .5em;
}
h1 {
text-align: center;
margin: .5em 0;
}
label {
float: left;
width: 10em;
text-align: right;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
#faqs h1 {
position: relative;
left: -168px;
font-size: 125%;
color: blue;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
cursor: pointer;
background: url(images/plus.png) no-repeat left center;
}
h2.minus {
background: url(images/minus.png) no-repeat left center;
}
div.open {
display: block;
}
ul {
padding-left: 45px;
}
li {
padding-bottom: .25em;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
I can't figure out for the life of me why the animations work in a separate test file but when I use them now in my tip calculator they don't. I'm using Murach's Javascript and Jquery book but this section has been terribly hard to understand.
Your issue is that you include jQuery but later on in the global scope you redefine the $:
var $ = function(id) {
return document.getElementById(id);
}
Fiddle: http://jsfiddle.net/AtheistP3ace/u0von3g7/
All I did was change the variable name holding that function and replace it in the areas you were using it. Specifically:
var getById = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var billAmount = parseFloat(getById("billAmount").value);
var percentTip = parseFloat(getById("percentTip").value);
var amountPeople = parseInt(getById("amountPeople").value);
if (isNaN(billAmount) || billAmount <= 0) {
alert("Your bill can't be 0 or less.");
} else if (isNaN(percentTip) || percentTip <= 0) {
alert("The percentage should be a whole number.");
} else if (isNaN(amountPeople) || amountPeople <= 0) {
alert("You are 1 person never count yourself as less.");
} else {
var total = billAmount * (percentTip / 100) / amountPeople;
getById("totalTip").value = total.toFixed(2);
}
}
window.onload = function() {
getById("calculate").onclick = calculateClick;
getById("billAmount").focus();
}
$ is just shorthand for jQuery. When you include jQuery it creates two functions for you that both do the same thing. jQuery and $. If you set $ equal to something else you have effectively overwritten jQuery library included in your page and it will no longer operate as you would expect. All jQuery functionality begins with using $ or jQuery function. Once that returns a jQuery object to you, you can begin chaining and calling functions off those objects but to get a jQuery object you need to use the jQuery or $ function.
You mentioned in a comment above your teacher had you do that to fix something. I imagine it was because jQuery was not initially included so he just created the $ selector function to get you moving but I would hope he explained why he did that and how it can affect things later.

10+1000 won't return the right number Javascript

I have a simple script asking a user for numbers.Each number is added into a variable called counter.I want this to happen as long as counter < 100
After that i want to show the user how many numbers he entered and the result.
The problem is that if the user presses 10 and the second time 1000 he will get back number 01001000
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Δομημένος προγραμματισμός</title>
<meta charset="utf-8"/>
<!--<link rel="stylesheet" type="text/css" href="http://kounj.web44.net/css/apps/borderRadius.css">-->
<style type="text/css">
button, .button {
border: 0px;
padding: 15px;
font-size: 18px;
color: green;
font-style: italic;
font-family: sans-serif;
border-radius: 6px;
border-left:4px dashed #f22aa9;
background-color: #ddd;
margin: 0;
display: inline-block;
}
.button{
display: block;
width: 20%;
}
</style>
<script type="text/javascript">
function wh(){
var i=0;
var counter=0;
while(counter < 100){
i++;
var number=prompt("Give me num");
counter=counter +number;
}
alert(i);
alert(counter);
}
</script>
</head>
<body>
<div class="button" onclick="wh();">counter</div>
</body>
</html>
You are concatenating strings. Any data input in a prompt is treated as a string. You need to convert to integer using parseInt() before adding to get proper integer math.
function wh(){
var i = 0;
var counter = 0;
while(counter < 100){
i++;
var input = prompt("Give me num");
var number = parseInt(input, 10);
counter = counter + number;
}
alert(i);
alert(counter);
}

Categories