I am new to javascript and I was trying to build a small guesser game app; however, every thing is Ok except for reloading the page after the game is over, the page is not reloading when clicking 'Play Again' and the button end up just disabled.
Please help me with this issue, I can not figure it out on my own.
let min = 1, max = 10, winnerNum = RandNum(max,min), gussNum = 3;
// UI vars
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
gussBtn = document.querySelector('#gussBtn'),
gussInput = document.querySelector('#input'),
message = document.querySelector('.msg');
// assign min and max
minNum.textContent = min;
maxNum.textContent = max;
// reload the game
game.addEventListener('mousedown', function(e){
if(e.target.className ==='play-again'){
window.location.reload();
// Why is the page is not reloaded ??
}
});
// listent to the gussed number
gussBtn.addEventListener('click', function(){
let guss = parseInt(gussInput.value);
console.log(guss);
//validate
if(guss===winnerNum){
gameOver(true,`Winner Winner Chicken Dinner, Yes ${winnerNum} is the correct number`)
} else{
gussNum -= 1;
if(gussNum===0){
gameOver(false,`You lost game over, the correct number is ${winnerNum}`)
} else if(gussNum<0){
gussBtn.disabled=true;
gussInput.disabled=true;
} else {
gussInput.disabled=true;
gussInput.style.borderColor = 'red';
gussInput.value = '';
setMessage(`You have ${gussNum} left!`, 'red')
}
}
});
function gameOver(won,msg){
let color;
won === true ? color = 'green' : color='red';
gussInput.disabled=true;
gussInput.style.borderColor = color;
// gussBtn.disabled=true;
setMessage(msg, color);
gussBtn.value='Play Again';
gussBtn.classList.add('play-again');
}
function RandNum(max,min) {
return Math.floor(Math.random()*(max-min+1)-min);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
}
HTML
<body>
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="card card-body text-center mt-5">
<h1 class="heading display-5 pb-3">Game Gusser</h1>
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<div class="form-group" id="game">
<div class="input-group">
<input type="number" class="form-control" id="input" placeholder="Enter your guess...">
<input type="submit" class="btn btn-dark btn-block mt-4" id="gussBtn">
</div>
<p class="msg mt-4"></p>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/app.js"></script>
</body>
I want when clicking Play Again btn the page reloads and user can play it again.
It is possible that the className is not exactly 'play-again'.
Also why not simply 'click' event?
function hasClass ( elem , klass ) {
return (" " + elem.className + " " ).indexOf( " " + klass + " " ) > -1
};
let game = document.getElementById('game');
game.addEventListener('click', function(e){
if (hasClass(e.target , 'play-again')){
window.location.reload();
}
});
Would also recommend against using location.reload(). Extremely bad user experience. Why not simply re-run the script that initializes the game in the first place?
Related
I have tried a bunch of ways to get this to work. I'm not a coder, and I have a frankensteined abomination of a counter program I put together as a replacement for our expensive counters that kept breaking on us (basically you input a value at the start of the day, and based on that value a calculation is done for the GOAL for the day).
I now want to add a GOAL BY LUNCH field/display that - however simply doing something like
var lunchgoal = goal * 0.69;
And then putting it on the page like I have with the goal field, does not seem to work.
I can either get it to display 0 - which seems like its displaying just the basic 0 value of goal before it is being incremented, or NaN - not a number.
So I thought I need to convert it to a number before multiplying it, but I nothing has worked for me for that. Right now I'm guessing it may be a matter of where they are contained on the page? I find that part of this confusing honestly. Any help is much appreciated, I would have thought this would be fairly simple!
Thank you!
HTML
<html>
<style>
body {background-color: Black;}
p {color: white;}
</style>
<div class="container">
<p> SAMS VALUE: <span id="output"> </span>
</p>
<p style="font-size:110px"> GOAL: <span id="output2"> </span>
</p>
<button style="background-color:white;width:20%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:110px">Actual Count: <span id="clicks">0</span>
</p>
<div class="row">
<div class="col-sm-4"/>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"/>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"/>
</div>
</div>
</div>
</html>
Script
<script type="text/javascript">
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
}
}, SAMSINPUT * 1000);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false,
t;
</script>
You have to do it in loop where goal is changing & you want this to change as well.otherwise it just stays on 0. i shortened the timer for demo purpose
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
// console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
var lunchGoalNumber = goal * 0.69;
var output3 = document.getElementById("output3")
output3.innerHTML = lunchGoalNumber;
}
}, SAMSINPUT * 25);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false;
<div class="container">
<p> SAMS VALUE: <span id="output"> </span></p>
<p style="font-size:50px"> GOAL: <span id="output2"> </span></p>
<p style="font-size:50px"> Lunch/GOAL: <span id="output3"> </span></p>
<button style="background-color:white;width:35%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:50px">Actual Count: <span id="clicks">0</span></p>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"></time>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"></div>
</div>
</div>
</div>
</body>
Please excuse me as if this seems like a simple question. I want to update the sum every time the space bar key is pressed down along with updating the innerHTML. Whenever I press the spacebar it just concatenates my sum variable instead of simply adding it.
HTML
<div class="sec1 sec">
<h1>Spacebar Challenge</h1>
</div>
<div class="sec2 sec">
<p>
You have hit the spacebar <span>0</span> times.
</p>
<div class='button'><button>Restart</button> </div>
</div>
<div class="sec3 sec"></div>
<script src="app.js"></script>
JS
let span = document.querySelector("span")
document.body.addEventListener("keyup", function (e) {
let sum = 0
if (e.code === "Space") {
sum += 1
}
span.innerHTML += sum
})
Try:
let span = document.querySelector("span")
let sum = 0
document.body.addEventListener("keyup", function(e) {
if (e.code === "Space") {
sum += 1
}
span.innerHTML = sum
})
<div class="sec1 sec">
<h1>Spacebar Challenge</h1>
</div>
<div class="sec2 sec">
<p>
You have hit the spacebar <span>0</span> times.
</p>
<div class='button'><button>Restart</button> </div>
</div>
<div class="sec3 sec"></div>
<script src="app.js"></script>
I'm totally new to web dev and trying to learn and practice Javascript.
I've learned a trick to change displayed image by changing the src of the image (they are named: pic-0.jpg, pic-1.jpg, pic-2.jpg... so on) but somehow my code won't work.
Anyone can have a look at my codes, help me out and give me some advice. I'd appreciate it!
Here are the codes:
var counter = 0;
document.getElementById('btn-next').addEventListener('click', changeImg);
function changeImg() {
counter++;
document.getElementById('picture').src = 'pic-' + counter + '.jpg';
}
<body>
<section class="container">
<div class="picture-container">
<img src="pic-0.jpg" id="picture" alt="">
</div>
<button id="btn-previous">Previous</button>
<button id="btn-next">Next</button>
</section>
<script src="r.js"></script>
</body>
cheers and many thanks!
you are using getElementsById , you should use getElementById because id is always unique and one page can have only one id , you can use getElementsByClassName because class can be attached more than one tag
var counter = 0;
document.getElementById('btn-next').addEventListener('click', changeImg);
function changeImg() {
counter++;
document.getElementById('picture').src = 'pic-' + counter + '.jpg';
document.getElementById('picture').alt = 'pic-' + counter + '.jpg';
}
<body>
<section class="container">
<div class="picture-container">
<img src="pic-0.jpg" id="picture" alt="df">
</div>
<button id="btn-previous">Previous</button>
<button id="btn-next">Next</button>
</section>
<script src="r.js"></script>
</body>
//---------------------JavaScript---------------
<body>
<section class="container">
<div class="picture-container">
<img src="https://i.picsum.photos/id/1/5616/3744.jpg" id="picture" height=50 width=50 alt="df">
</div>
<button id="btn-previous">Previous</button>
<button id="btn-next">Next</button>
</section>
<script>
var counter = 1;
document.getElementById('btn-next').addEventListener('click', nextImg);
document.getElementById('btn-previous').addEventListener('click',preImg);
function nextImg() {
counter++;
document.getElementById('picture').src = 'https://i.picsum.photos/id/' + counter + '/5616/3744.jpg';
}
function preImg() {
counter--;
document.getElementById('picture').src = 'https://i.picsum.photos/id/' + counter + '/5616/3744.jpg';
}
</script>
</body>
I think the best thing is store all of your images path into an array. Then
var imgArr = ["1.jpg", "2.jpg"]
var counter = 0;
function changeImg(evt) {
if(evt === 'prv'){
if(counter === 1)
counter++;
else
counter--;
}
else{
if(counter === (imgArr.length))
counter = 1;
else
counter++;
}
document.getElementById('picture').src = imgArr[counter];
}
<section class="container">
<div class="picture-container">
<img src="" id="picture" alt="">
</div>
<button id="btn-previous" onClick="changeImg('prv')">Previous</button>
<button id="btn-next" onClick="changeImg('nxt')">Next</button>
</section>
I just don't know how to use IF condition here i use bubble chat too ,so when the textfield is empty the bubble chat gets updated without any texts.i don't want it.So how to use IF condition for it properly.
window.onload = function() {
document.getElementById("myText").focus();
};
function typo(){
var currentText = document.getElementById("demo").innerHTML;
var x = '<div><p class=bubble>' + document.getElementById("myText").value + '</p></div>';
document.getElementById("myText").value = "";
var y = document.getElementById("demo").innerHTML = currentText + x;
var z = document.getElementById('demo');
z.scrollTop = z.scrollHeight;
}
var input = document.getElementById("myText");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("btn-chat").click();
}
});
<div class="container">
<div class="row">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span> Chat
<div class="btn-group"></div>
</div>
</div>
</div>
<div class="bottom">
<p id="demo"></p>
<input class="widebox" type="text" id="myText" value="">
<button onclick="typo()" class="btn btn-warning btn-sm" id="btn-chat">Send</button>
</div>
</div>
here's the demo fiddle here
You can check to make sure there is at least a length of 1 char.
After looking at your demo you added, you can also make sure white space is gone by using trim() to check.
if (event.keyCode === 13 && input.value.trim().length > 0) {
https://jsfiddle.net/kkjbryqe/8/
if (event.keyCode === 13 && input.value.length)... could work?
i posted a demo in fiddle below my question ..So that i can be more clear of what am doing and thanks everyone for the time to look through my question and helping me out.I really appreciate
I've one div that contains to other one:
<div>
<div id="card-container">....</div>
<div id="wait-for-result-container" style="display: none;">...</div>
</div>
On some event, I want to change the displayed element, with a fadeIn/fadeOut effect.
$('#card-container').hide(5000);
$('#wait-for-result-container').show(5000);
(I put some big number to really see the effect)
But when I trigger my effect, it is instantaneous, there is no fade-in/fade-out.
I'm not sure it matters, but I'm using jquery-3.1.1 and bootstrap 4 alpha.
Any idea what is going wrong?
EDIT
As asked, here is some clarification.
The element that I'm trying to hide is hided immediatly and the one I show is appearing immediately.
EDIT
I tried to put a demo here with the code from above:
$('#myBt').click(function(){
$('#card-container').hide(5000);
$('#wait-for-result-container').show(5000);
});
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Click me</button>
If you can use the full version of jQuery, give jQuery fadeOut and fadeIn a try :)
$('#myBt').click(function(){
var duration = 5000;
$('#card-container').fadeOut(duration);
$('#wait-for-result-container').delay(duration).fadeIn(duration);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Example1</button>
If you have to stick with the slim version, you can use setInteval
$('#myBt').click(function(){
var duration = 5000;
var op = 0.9; // initial opacity
var timer1 = setInterval(function () {
if (op <= 0.1){
clearInterval(timer1);
op = 0;
$('#card-container')[0].style.display = 'none';
}
$('#card-container')[0].style.opacity = op;
op -= 100/duration;
}, 100);
var timer2 = setInterval(function () {
if (op <= 0){
$('#wait-for-result-container')[0].style.opacity = 0;
$('#wait-for-result-container').show();
}
if (op >= 1){
clearInterval(timer2);
}
if($('#wait-for-result-container').is(':visible')){
$('#wait-for-result-container')[0].style.opacity = op;
op += 100/duration;
}
}, 100);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Example2</button>