Why does my application keep running? - javascript

I'm making a Whack-A-Mole game and i'm currently stuck with this problem : My game keeps running after lives are < 0 , I'm just wondering if anyone wants to take a look at my code ( the inAction boolean in particular) and can tell me what I'm doing wrong , I'm just learning :) Here is my code :
#moleWorld {
height: 330px;
width: 1500px;
margin: 0 auto;
border: 1px solid black;
}
.field {
display: inline-block;
width: 21%;
margin: 27px;
height: 21%;
border: 1px solid black;
background: red;
}
.mole {
display: inline-block;
width: 21%;
margin: 27px;
height: 21%;
border: 1px solid black;
background-color: green;
}
#generalInformation {
height: 40px;
width: 330px;
margin: 0 auto;
background: lightblue;
}
#level-display,
#lifes-display {
margin-left: 30px;
}
#beginEasyClick,
#beginNormalClick,
#beginHardClick {
margin: 40px 45%;
width: 70px;
height: 30px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../jquery-3.1.1.js">
"use strict";
var currentScore = 2;
var niveau = 0;
var currentLives = 3;
var inAction = false;
var moleworld = "#moleWorld";
var beginEasyClick = document.getElementById("beginEasyClick");
var beginNormalClick = document.getElementById("beginNormalClick");
var beginHardClick = document.getElementById("beginHardClick");
var displayScore = document.getElementById("_displayScore");
var $field = $(moleworld).find(class = "field")
var getrandomInt(function(min, max) {
return Math.floor(Math.random() * (max - min - 1)) + min
})
function randomField() {
return Math.floor(Math.random() * 8)
}
</script>
<script>
var moleworld = "#moleWorld";
var $moleworld = $(moleworld);
currentScore = 0;
currentLives = 5;
inAction = false;
"use strict";
$().ready(function() {
$(beginEasyClick).click(function() {
if (!inAction) {
inAction = true
setInterval(function() {
spawnMole();
}, 1400);
showScore();
isThisTheMole();
}
});
function spawnMole() {
var oldScore = currentScore;
var allFields = new Array();
allFields = document.getElementsByClassName("field")
var target = $(allFields[Math.floor(Math.random() * allFields.length)])
target.addClass("mole");
setTimeout(function() {
target.removeClass("mole")
if (oldScore === currentScore) {
currentLives--;
checkLives();
}
showScore();
}, 1000)
}
function showScore() {
document.getElementById("_displayScore").innerHTML = "<span> Score : " + currentScore + " Lives : " + currentLives + "</span>"
}
$(beginNormalClick).click(function() {
// $("#car").css("background-color" , "green");
inAction = false;
});
function isThisTheMole() {
$("div>div").click(function() {
var clickedField = $(this);
if (clickedField.hasClass("mole")) {
currentScore++;
clickedField.removeClass("mole");
} else {
currentLives--;
}
showScore();
checkLives();
})
}
function checkLives() {
if (currentLives === 0) {
alert("")
inAction = false;
}
}
});
</script>
<p id="car" class="kes">blablacar</p>
<p class="kes">carblabla </p>
<div id="StartMenu"></div>
<button id="beginEasyClick"> Easy </button>
<button id="beginNormalClick"> Normal </button>
<button id="beginHardClick"> Hard </button>
<div id="generalInformation">
<p id="_displayScore"> </p>
</div>
<div id="moleWorld">
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
Thank you very much for reading!

In your code I found several mistakes. Please rewrite your code one by one.
1) For your HTML Code:
You missed to end the for Id moleWorld
<div id="moleWorld">
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
Correct Code will be:
<div id="moleWorld">
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
</div>
2) After Including the jQuery Library file you again tried to include include jQuery
Your Code was : <script type="text/javascript" src="../jquery-3.1.1.js">
Correction Code: <script type="text/javascript">
3) You are trying to find the class name from id moleWorld but in a wrong way without semicolon ;.
Your code was: var $field = $(moleworld).find(class = "field")
Correction code: var $field = $(moleworld).find('.field');
4) You are trying to declare a function inside of another function in a wrong way.
Your code was: var getrandomInt(function(min, max) {
return Math.floor(Math.random() * (max - min - 1)) + min
});
Suggested Code: var getrandomInt = (function(min, max) {
return Math.floor(Math.random() * (max - min - 1)) + min;
});
Now you can use your getrandomInt variable as a function
5) your document ready method is not correct.
You wrote: $().ready(function() {...});
It will be: $(document).ready(function() {...});
Note: Please try to use semicolon after your line end.
Run it and hope it will work now. For me it's now working.
Thanks

You need to reset your interval with clearInterval():
var currentScore = 0;
var currentLives = 0;
var inAction = false;
var interval = null;
var allFields = document.getElementsByClassName("field");
function start(lives) {
if (inAction) {
console.log('Already in action, ignore request');
return;
}
currentScore = 0;
currentLives = lives;
inAction = true;
console.log('Start interval');
// Store interval id to be able to clear it later
interval = setInterval(function () {
spawnMole();
}, 1400);
showScore();
isThisTheMole();
}
function stop() {
console.log('Stop interval');
inAction = false;
clearInterval(interval);
}
function spawnMole() {
var oldScore = currentScore;
var target = $(allFields[Math.floor(Math.random() * allFields.length)]);
target.addClass("mole");
setTimeout(function () {
target.removeClass("mole");
if (oldScore === currentScore) {
currentLives--;
checkLives();
}
showScore();
}, 1000);
}
function showScore() {
// Use jQuery as it's already loaded
$("#displayScore").html("<span> Score : " + currentScore + " Lives : " + currentLives + "</span>");
}
function isThisTheMole() {
// Only listen on relevant divs
$("div#moleWorld > div.field").click(function () {
// Ignore click if the game is running
if (!inAction) return;
var clickedField = $(this);
if (clickedField.hasClass("mole")) {
currentScore++;
clickedField.removeClass("mole");
} else {
currentLives--; // Double penalty
}
showScore();
checkLives();
})
}
function checkLives() {
if (currentLives <= 0) { // lives could be below zero in case of double penalty
console.log('No more lifes remaining');
stop();
}
}
$(function() {
// Use jQuery as it's already loaded
$('#beginEasyClick').click(function () {
start(5);
});
$('#beginNormalClick').click(function () {
start(2);
});
});
#moleWorld {
height: 330px;
width: 1500px;
margin: 0 auto;
border: 1px solid black;
}
.field {
display: inline-block;
width: 21%;
margin: 27px;
height: 21%;
border: 1px solid black;
background: red;
}
.mole {
display: inline-block;
width: 21%;
margin: 27px;
height: 21%;
border: 1px solid black;
background-color: green;
}
#generalInformation {
height: 40px;
width: 330px;
margin: 0 auto;
background: lightblue;
}
#level-display, #lifes-display {
margin-left: 30px;
}
#beginEasyClick , #beginNormalClick, #beginHardClick {
margin: 40px 45%; width: 70px;height: 30px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="car" class="kes">blablacar</p>
<p class="kes">carblabla </p>
<div id="StartMenu"></div>
<button id="beginEasyClick"> Easy </button>
<button id="beginNormalClick"> Normal </button>
<button id="beginHardClick"> Hard </button>
<div id="generalInformation"><p id="displayScore"></p></div>
<div id="moleWorld">
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
<div class="field"> </div>
</div>
(I've removed some unused stuff)

Related

Simple conditional for handling the Tags (JQuery , javascript)

I want to write a conditional to handle tags.
$("#btn").click(function() {
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 9 + Math.random() * 100);
$('#div2').html(number);
var $div3 = $("#div3");
if (number > 50) {
var span1 = $('<span />').addClass('yes').text('YES');
span1.appendTo($div3);
checkSpan(span1);
} else {
var span2 = $('<span />').addClass('no').text(' NO');
span2.appendTo($div3);
}
}, 1000);
});
function checkSpan($span) {
if ($span.prevUntil('.no', '.yes').length === 2) {
[].forEach.call(document.querySelectorAll('.yes'), function(e) {
e.parentNode.removeChild(e);
});
[].forEach.call(document.querySelectorAll('.no'), function(e) {
e.parentNode.removeChild(e);
});
var Reset = $('<span />').addClass('reset').text("RESET");
Reset.appendTo($("#div3"));
}
}
.yes,
.no,
.reset {
display: inline-block;
padding: 5px;
text-align: center;
margin: 1px;
}
.yes {
background-color: green;
color: white;
}
.no {
background-color: red;
}
.reset {
background-color: #5f79ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1" style="background-color: #cce1ee;text-align: center;width: 500px;height: 500px;margin: 0 auto;">
<input id="btn" value="click" type="button" style="' + 'text-align: center;width: 50px" />
<div id="div2"></div>
<div id="div3"></div>
</div>
here we see after (3 <span class="yes">YES</span>) all spans tag with class .yes and .no will be remove
and the this <span class="reset">RESET</span> is created .
now i want a conditional => if after <span class="reset">RESET</span> is there <span class="yes">YES</span> ?
if yes?
so alert ("there is span tag with class yes after Reset")
else {
alert ("there is no span tag with class yes after Reset")
}
Example :
if
<span class="reset">Reset</span>
<span class="yes">YES</span>
do stuff ....
If i understand what you want:
$("#btn").click(function() {
var nbyes = 0;
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 9 + Math.random() * 100);
$('#div2').html(number);
var $div3 = $("#div3");
if (number > 50) {
if(nbyes == 3){
nbyes = 0;
alert("there is span tag with class yes after Reset");
}
var span1 = $('<span />').addClass('yes').text('YES');
span1.appendTo($div3);
nbyes++;
if(nbyes == 3){
checkSpan();
}
} else {
if(nbyes == 3){
nbyes = 0;
alert("there is no span tag with class yes after Reset");
}
var span2 = $('<span />').addClass('no').text(' NO');
span2.appendTo($div3);
}
}, 1000);
});
function checkSpan($span) {
$(".yes, .no").remove();
var Reset = $('<span />').addClass('reset').text("RESET");
Reset.appendTo($("#div3"));
}
.yes,
.no,
.reset {
display: inline-block;
padding: 5px;
text-align: center;
margin: 1px;
}
.yes {
background-color: green;
color: white;
}
.no {
background-color: red;
}
.reset {
background-color: #5f79ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1" style="background-color: #cce1ee;text-align: center;width: 500px;height: 500px;margin: 0 auto;">
<input id="btn" value="click" type="button" style="' + 'text-align: center;width: 50px" />
<div id="div2"></div>
<div id="div3"></div>
</div>

.click only if div contains 2 specific divs

I have a an on.click, but I want it to only run if #battle contains #obiWanPicked and #darthMaul. For whatever reason it seems to be ignoring the if statement and running the click, no matter what.
Most of my html content is dynamically created in JavaScript, thats why I start using .on instead of .click lower down when I'm manipulating objects dynamically created.
if ($("#battle").has("#obiWanPicked") && $("#battle").has("#darthMaul")) {
$("#battle").on("click", "#attack", function () {
if(darthMaulStats.healthPoints <= 0){
$("#darthMaul").remove();
alert("You win!");
}
darthMaulStats.healthPoints = darthMaulStats.healthPoints - obiWanStats.attackPower;
obiWanStats.attackPower = obiWanStats.attackPower + 15;
$("#darthMaul").text(darthMaulStats.healthPoints);
obiWanStats.healthPoints = obiWanStats.healthPoints - 5;
$("#obiWanPicked").text(obiWanStats.healthPoints);
console.log(obiWanStats);
$('#yourFighters').remove();
});
}
All of the above code
<div id="gameModule">
<div class="row">
<div class="col-2"></div>
<div class="col-8">
<div id="allFighters">Pick your Fighter!<br /></br>
<div id="obiWan">
<h2>120</h2>
</div>
<div id="darthMaul">
<h2>150</h2>
</div>
<div id="hanSolo">
<h2>100</h2>
</div>
<div id="maceWindu">
<h2>200</h2>
</div>
</div>
</div>
<div id="col-2"></div>
</div>
<div id="row">
<div id="yourFighters"></br>Your Pick<br></div>
</div>
<div id="row">
<div id="enemyFighters">Your Enemies: Click to fight<br></div>
</div>
<div id="row">
<div id="battle">Time to Battle!</br><br></div>
</div>
<div id="row">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="footer">
<br />
FOOTER
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
var allFighters = $('#allFighters');
var yourFighters = $('#yourFighters');
var enemyFighters = $('#enemyFighters');
var battle = $('#battle');
var obiWan = $('#obiWan');
var darthMaul = $('#darthMaul');
var darthMaulBattle = $('#darthMaulBattle');
var hanSolo = $('#hanSolo');
var maceWindu = $('#maceWindu');
var attack = $('#attack')
var obiWanStats = {
healthPoints: 120,
attackPower: 15,
counterAttackPower: 14,
};
var darthMaulStats = {
healthPoints: 150,
attackPower: 15,
counterAttackPower: 14,
};
var hanSoloStats = {
healthPoints: 100,
attackPower: 15,
counterAttackPower: 14,
};
var maceWinduStats = {
healthPoints: 200,
attackPower: 15,
counterAttackPower: 14,
};
console.log(maceWinduStats.healthPoints);
obiWan.click(function () {
allFighters.remove();
yourFighters.append("<div id='obiWan'>120</div><h1>");
enemyFighters.append("<div id='darthMaul'>150</div>");
enemyFighters.append("<div id='hanSolo'>100</div>");
enemyFighters.append("<div id='maceWindu'>200</div>");
battle.append("<div id='obiWanPicked'>" + obiWanStats.healthPoints + "</div> <p style='color: red; padding-left: 500px; padding-right: 500px; text-decoration: overline; '>VERSUS");
});
darthMaul.click(function () {
allFighters.remove();
yourFighters.append("<div id='darthMaul'>120</div>");
enemyFighters.append("<div id='obiWan'>150</div>");
enemyFighters.append("<div id='hanSolo'>100</div>");
enemyFighters.append("<div id='maceWindu'>200</div>");
battle.append("<div id='darthMaulPicked'>" + darthMaulStats.healthPoints + "</div> <p style='color: red; padding-left: 500px; padding-right: 500px; text-decoration: overline; '>VERSUS");
});
hanSolo.click(function () {
allFighters.remove();
yourFighters.append("<div id='hanSolo'>120</div>");
enemyFighters.append("<div id='darthMaul'>150</div>");
enemyFighters.append("<div id='obiWan'>100</div>");
enemyFighters.append("<div id='maceWindu'>200</div>");
battle.append("<div id='hanSoloPicked'>" + hanSoloStats.healthPoints + "</div> <p style='color: red; padding-left: 500px; padding-right: 500px; text-decoration: overline; '>VERSUS");
});
maceWindu.click(function () {
allFighters.remove();
yourFighters.append("<div id='maceWindu'>120</div>");
enemyFighters.append("<div id='darthMaul'>150</div>");
enemyFighters.append("<div id='hanSolo'>100</div>");
enemyFighters.append("<div id='obiWan'>200</div>");
battle.append("<div id='maceWinduPicked'>" + maceWindu.healthPoints + "</div> <p style='color: red; padding-left: 500px; padding-right: 500px; text-decoration: overline;'>VERSUS");
});
$("#enemyFighters").on("click", "#darthMaul", function () {
$(this).remove();
console.log("meme");
battle.append("<div id='darthMaul' style='float: none; margin-left: 50%; margin-top: -35px;'>" + darthMaulStats.healthPoints + "</div><div id='attack'>Attack!</div>");
});
$("#enemyFighters").on("click", "#hanSolo", function () {
$(this).remove();
console.log("meme");
battle.append("<div id='hanSolo' style='float: none; margin-left: 50%; margin-top: -35px;'>" + hanSoloStats.healthPoints + "</div><div id='attack'>Attack!</div>");
});
$("#enemyFighters").on("click", "#maceWindu", function () {
$(this).remove();
console.log("meme");
battle.append("<div id='maceWindu' style='float: none; margin-left: 50%; margin-top: -35px;'>" + maceWinduStats.healthPoints + "</div><div id='attack'>Attack!</div>");
});
$("#enemyFighters").on("click", "#obiWan", function () {
$(this).remove();
console.log("meme");
battle.append("<div id='obiWan' style='float: none; margin-left: 800px; margin-top: -35px;'>" + obiWanStats.healthPoints + "</div><div id='attack'>Attack!</div>");
});
Maybe you are trying to do something like this. Using find and testing the length should work.
/* Maybe you are trying to do something like this. Using find and testing the length should work. */
$("#battle").on("click", "#attack", function () {
if ($("#battle").find("#obiWanPicked").length > 0 && $("#battle").find("#darthMaul").length > 0){
console.log("You win!");
} else {
console.log("You Lose!");
}
});
/* Just for testing */
$("body").on("click", "#toggleObiwan", function(){
if($("#battle").find("#obiWanPicked").length > 0){
$("#obiWanPicked").remove();
} else {
$("#battle").append("<div id='obiWanPicked'>O</div>");
}
});
$("body").on("click", "#toggleDarthMaul", function(){
if($("#battle").find("#darthMaul").length > 0){
$("#darthMaul").remove();
} else {
$("#battle").append("<div id='darthMaul'>D</div>");
}
});
#battle {
width: 200px;
height: 100px;
background: green;
}
#obiWanPicked {
width: 20px;
height: 20px;
background: skyblue;
line-height: 20px;
margin: 5px;
}
#darthMaul {
width: 20px;
height: 20px;
background: red;
line-height: 20px;
margin: 5px;
}
button {
width: 100px;
font-size: 11px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<button id="toggleObiwan">TOGGLE OBIWAN</button>
<button id="toggleDarthMaul">TOGGLE DARTH MAUL</button>
<div id="battle">
<button id="attack">ATTACK</button>
<div id="obiWanPicked">O</div>
<div id="darthMaul">D</div>
</div>
Not sure here... I'm kind of replying quick. But I understand your question from this:
I want it to only run if #battle contains #obiWanPicked and #darthMaul
Now the click handler is registered on page load where (I suppose) the two ids to be checked for existance are there.
Move that condition in the click handler!
$("#battle").on("click", "#attack", function () {
if ($("#battle").has("#obiWanPicked").length && $("#battle").has("#darthMaul").length) {
if(darthMaulStats.healthPoints <= 0){
//...
So the condition will be checked on every click instead of only when the handler gets registered.
;)
showdev mentionned a good point... Add .length after has(), so the condition will evaluate on length instead of on an object.
A zero length evaluates to false. Any other lenght evaluates to true.

JavaScript moving text animation doesn't work. FULL CODE

JS: My problem is in running the following JS script, it's supposed to be very easy ,i think, but i can't understand why won't it run. I've just started coding and i'm already stuck in this problem. I want the text to go up (by increasing the bottom in CSS) for 5px until it reaches pos=6 ; then clearInterval should do its job.
CSS: I've put the position of div's to RELATIVE as i've read in some tutorials but didn't put the " container's " position to ABSOLUTE, may it be the problem?
<html>
<head>
<style>
html {
height: 100%;
}
body {
height: ;
width: 100%;
background-color: ;
margin: 0px;
padding: 0px;
}
#generale {
height: 100%;
width: 100%;
}
#intestazione {
height: 7%;
width: 100%;
float: left;
background-image: url(immagini/sfumatura.png);
position: static;
}
#profilo {
position: static;
float: right;
width: 12%;
height: 100%;
}
.testo_rialzato {
position: relative;
float: right;
width: auto;
height: 100%;
padding-left: 20px;
padding-right: 20px;
background-color: transparent;
}
</style>
</head>
<body>
<div id="generale">
<div id="intestazione">
<div id="profilo"></div>
<div class="testo_rialzato sumba">
<p>Sp</p>
</div>
<div class="testo_rialzato ap">
<p>App</p>
</div>
<div class="testo_rialzato te">
<p>Te</p>
</div>
<div class="testo_rialzato do">
<p>Dom</p>
</div>
<div class="testo_rialzato big">
<p style="line-height:70%; margin-top:8px; text-align:center;">Big</p>
</div>
</div>
<script>
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
ez.onmouseover = alza();
var intervallo = setInterval(alza, 100);
function alza() {
var pos = 0;
if (pos = 6) {
clearInterval(intervallo);
} else {
ez.style.bottom = pos + "px";
}
}
</script>
</div>
</body>
</html>
First thing is , why declaring you are using event on an array of dome node (result of querySelectorAll will return array of domenodes ) so in order to attach mouseover and also apply some style you have to loop around those nodes .
Seconde thing while declaring set interval, its usless to use mousemovehere ?
Also the condition if is wrong you're using assignment , so you have to use == or === in order to make comaparison .
See below snippet :
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
var pos = 0;
var intervallo = setInterval(alza, 100);
ez.forEach(function(el){
el.addEventListener("mouseover", alza);
})
function alza() {
if (pos == 25) {
clearInterval(intervallo);
} else {
ez.forEach(function(el){
el.style.bottom = pos + "px";
});
pos++;
}
}
.sumba, .ap {
position:absolute;
}
.ap {
color:red;
left:40px
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="sumba">Text</div>
<div class="ap">Text 2</div>
try this
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
}
</style>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate">ggg</div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>

Accordion close animation not working. It opens (with animation) and closes (with no animation)

I'm pretty new to javascript, so this might be a dumb question.
My open Animation works great, but the close animation doesn't work/fire.
it should just be as simple as reversing the animation, but that doesn't seem to work.
I have to be missing something here. Is there a better way to do this?
Been trying to figure this out all day.
HTML
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell">
<button type="button" id="id" onclick="btnDetails_Click('id')">
<p id="id-ButtonText">Details ▼</p>
</button>
</div>
<div class="divTableCell">
<p>Name</p>
</div>
<div class="divTableCell">
<p>Details</p>
</div>
</div>
<div class="divTableFoot" style="display:none" id="id-DetailsPanel">
<div class="divTableCell" style="display:flex; height:0; overflow:hidden" id="id-DetailsPanel2">
<div style="margin-right:20px">
<img style="height:400px" src="http://via.placeholder.com/200x400" />
</div>
<div style="width:auto">
<p>Description</p>
</div>
</div>
</div>
</div>
</div>
CSS
/* DivTable.com */
.divTable {
display: table;
width: 100%;
}
.divTableRow {
display: table-row;
}
.divTableHeading {
background-color: #EEE;
display: table-header-group;
}
.divTableCell,
.divTableHead {
border: 1px solid #999999;
display: table-cell;
padding: 3px 10px;
}
.divTableHeading {
background-color: #EEE;
display: table-header-group;
font-weight: bold;
}
.divTableFoot {
width:100%;
}
.divTableBody {
display: table-row-group;
}
JavaScript
function btnDetails_Click(id) {
document.getElementById("id-DetailsPanel").style = "display:inherit";
document.getElementById("id").setAttribute("onclick", "btnDismiss_Click('id')");
document.getElementById("id-ButtonText").innerHTML = "Details ▲";
expand(id)
}
function btnDismiss_Click(id) {
contract(id)
document.getElementById("id-ButtonText").innerHTML = "Details ▼";
document.getElementById("id").setAttribute("onclick", "btnDetails_Click('id')");
document.getElementById("id-DetailsPanel").style = "display:none";
}
function expand(id) {
var detailsBox = document.getElementById("id-DetailsPanel2");
var boxHeight = 0;
var int = setInterval(animate, 8);
function animate() {
if (boxHeight == 425) {
clearInterval(int);
} else {
boxHeight = boxHeight + 25;
detailsBox.style.height = boxHeight + 'px';
}
}
}
function contract(id) {
var detailsBox = document.getElementById("id-DetailsPanel2");
var boxHeight = 425;
var int = setInterval(animate, 8);
function animate() {
if (boxHeight == 0) {
clearInterval(int);
} else {
boxHeight = boxHeight - 25;
detailsBox.style.height = boxHeight + 'px';
}
}
}
here's the JSFiddle: https://jsfiddle.net/1zryo2Lp/
Because before the setInterval got a chance to execute document.getElementById("id-DetailsPanel").style = "display:none"; happened. A simple fix would be to move display:none line after clearInterval(int);
function btnDetails_Click(id) {
document.getElementById("id-DetailsPanel").style = "display:inherit";
document.getElementById("id").setAttribute("onclick", "btnDismiss_Click('id')");
document.getElementById("id-ButtonText").innerHTML = "Details ▲";
expand(id)
}
function btnDismiss_Click(id) {
contract(id)
document.getElementById("id-ButtonText").innerHTML = "Details ▼";
document.getElementById("id").setAttribute("onclick", "btnDetails_Click('id')");
// document.getElementById("id-DetailsPanel").style = "display:none";
}
function expand(id) {
var detailsBox = document.getElementById("id-DetailsPanel2");
var boxHeight = 0;
var int = setInterval(animate, 8);
function animate() {
if (boxHeight == 425) {
clearInterval(int);
} else {
boxHeight = boxHeight + 25;
detailsBox.style.height = boxHeight + 'px';
}
}
}
function contract(id) {
var detailsBox = document.getElementById("id-DetailsPanel2");
var boxHeight = 425;
var int = setInterval(animate, 8);
function animate() {
if (boxHeight == 0) {
clearInterval(int);
document.getElementById("id-DetailsPanel").style = "display:none";
} else {
boxHeight = boxHeight - 25;
detailsBox.style.height = boxHeight + 'px';
}
}
}
.divTable {
display: table;
width: 100%;
}
.divTableRow {
display: table-row;
}
.divTableHeading {
background-color: #EEE;
display: table-header-group;
}
.divTableCell,
.divTableHead {
border: 1px solid #999999;
display: table-cell;
padding: 3px 10px;
}
.divTableHeading {
background-color: #EEE;
display: table-header-group;
font-weight: bold;
}
.divTableFoot {
width:100%;
}
.divTableBody {
display: table-row-group;
}
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell">
<button type="button" id="id" onclick="btnDetails_Click('id')">
<p id="id-ButtonText">Details ▼</p>
</button>
</div>
<div class="divTableCell">
<p>Name</p>
</div>
<div class="divTableCell">
<p>Details</p>
</div>
</div>
<div class="divTableFoot" style="display:none" id="id-DetailsPanel">
<div class="divTableCell" style="display:flex; height:0; overflow:hidden" id="id-DetailsPanel2">
<div style="margin-right:20px">
<img style="height:400px" src="http://via.placeholder.com/200x400" />
</div>
<div style="width:auto">
<p>Description</p>
</div>
</div>
</div>
</div>
</div>

How to prevent page refresh on button click

I need help with my coin flip. Basically what I wanted to do is to create two buttons. By pressing one of them, the player would pick a side, for example Global or Fortune.
I can't figure out how to do it so when the player presses the button it will actually pick a side without refreshing the site.
var result, userchoice;
function resetAll() {
var resetHTML = '<div class="tail"><img src="coin_F.png" /></div><div class="head"><img src="coin_G.png" /></div>';
setTimeout(function() {
$('.coinBox').fadeOut('slow', function() {
$(this).html(resetHTML)
}).fadeIn('slow', function() {
$('#btnFlip').removeAttr('disabled');
});
}, 2500);
}
// Checking User Input
$(document).on('change', '#userChoice', function() {
userchoice = $(this).val();
if (userchoice == "") {
$(this).parent('p').prepend("<span class='text text-danger'>Please select a coin side to play the game</span>")
$('#btnFlip').attr('disabled', 'disabled');
} else {
/**/
$('#btnFlip').removeAttr('disabled');
$(this).siblings('span').empty();
}
return userchoice;
});
// Final result declaration
function finalResult(result, userchoice) {
var resFormat = '<h3>';
resFormat += '<span class="text text-primary">You choose : <u>' + userchoice + '</u></span> |';
resFormat += '<span class="text text-danger"> Result : <u>' + result + '</u></span>';
resFormat += '</h3>';
var winr = '<h2 class="text text-success" style="color: #49DF3E;">You Won!!</h2>';
var losr = '<h2 class="text text-danger" style="color: #c34f4f;">You Lost...</h2>';
if (result == userchoice) {
$('.coinBox').append(resFormat + winr)
} else {
$('.coinBox').append(resFormat + losr)
}
}
// Button Click Actions
$(document).on('click', '#btnFlip', function() {
if ($('#userChoice').val() == "") return;
var flipr = $('.coinBox>div').addClass('flip');
var number = Math.floor(Math.random() * 2);
$(this).attr('disabled', 'disabled');
setTimeout(function() {
flipr.removeClass('flip');
//result time
if (number) {
result = 'Global';
//alert('Head = '+number);
$('.coinBox').html('<img src="coin_G.png" /><h3 class="text-primary">Global</h3>');
finalResult(result, userchoice);
resetAll();
} else {
result = 'Fortune';
//alert('Tail = '+number);
$('.coinBox').html('<img src="coin_F.png" /><h3 class="text-primary">Fortune</h3>');
finalResult(result, userchoice);
resetAll();
}
}, 2000);
return false;
});
#wrapper
{
width: 100%;
height: auto;
min-height: 500px;
}
.btn
{
width: 12%;
background-color: #c34f4f;
color: white;
padding: 14px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 22px;
}
.btn:hover
{
background-color: #A64242;
}
input[type=submit]:hover {
background-color: #A64242;
}
.container
{
padding: 50px 0;
text-align: center;
}
h1
{
margin-bottom: 100px;
}
.head
{
margin-top: -205px;
}
.flip img{animation: flipIt 0.5s linear infinite;}
.head img
{
animation-delay: 0.25s;
}
#keyframes flipIt
{
0%{width: 0px;
height: 200px;}
25%{width: 200px;
height: 200px;}
50%{width: 0px;
height: 200px;}
100%{width: 0px;
height: 200px;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Coin Flip | <span>Global or Fortune</span></h1>
</div>
<div class="col-lg-12">
<!--blank-->
<div class="col-lg-4"></div>
<!--coin-->
<div class="col-lg-4">
<div class="coinBox">
<div class="tail">
<img src="coin_F.png" />
</div>
<div class="head">
<img src="coin_G.png" />
</div>
</div>
</div>
<!--user form elements-->
<div class="col-lg-4 text-left">
<p>
<div class="form-control">
<button name="Global" id="userChoice">Global</button>
<button name="Fortune" id="userChoice">Fortune</button>
</div>
<p>
<button class="btn btn-lg btn-primary" id="btnFlip" disabled>Flip It</button>
</p>
</div>
</div>
</div>
</div>
</div>
Try something like this:
HTML
<div class="choices">
<button name="Heads">Heads</button>
<button name="Tails">Tails</button>
<p>You have chosen: <span class="choice"></span></p>
</div>
<div class="flip">
<button class="disabled">Flip Coin</button>
<p></p>
</div>
CSS
.flip button {
background: #cc0000;
color: #fff;
padding: 5px;
}
.flip button.disabled {
cursor: not-allowed;
background: #ccc;
color: #eee;
}
JS
$(function() {
$(".choices button").on("click", function() {
var choice = $(this).attr("name");
//show selected choice
$(".choice").text(choice);
//enable flip button
$(".flip button").removeClass("disabled");
});
$(".flip button").on("click", function() {
//flip coin if a choice has been made
if(!$(this).hasClass("disabled")) {
//get random number
var flip = Math.floor(Math.random() * 2) + 1;
//determine side of coin and result of guess (ternary)
var flipSide = flip == 1 ? "Heads" : "Tails";
var result = flipSide == $(".choice").text() ? "correct" : "wrong";
//show flip result
$(".flip p").text(flipSide + ", you chose " + result);
}
});
});
You can also view it working here: https://jsfiddle.net/8jw1ogLd/

Categories