How to prevent page refresh on button click - javascript

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/

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>

I Want to connect an HTML Element To a javascript Object

For every product's <img> element on the page, I want to create an associated JavaScript object with attributes of title, description and price. When the <img> is clicked, it should show a modal based on a HTML template with the fields populated by these attributes.
Here is my current code:
document.getElementById("red").onclick = function() {functionRed()};
document.getElementById("yellow").onclick = function() {functionYellow()};
document.getElementById("blue").onclick = function() {functionBlue()};
// Create an object:
var Blue = {Title:"BlueIsTheNewBlack", Price:"500", Description:"This blue is the best color"}
var Yellow = {Title:"YellowIsTheNewBlack", Price:"900", Description:"This yellow is the best color"}
var Red = {Title:"RedIsTheNewBlack", Price:"100", Description:"This red is the best color"}
function functionRed() {
document.getElementById('id01').style.display='block';
// Display some data from the object:
document.getElementById("TitleModal").innerHTML = Red.Title;
document.getElementById("PriceModal").innerHTML = Red.Price;
document.getElementById("DescriptionModal").innerHTML = Red.Description;
}
function functionYellow() {
document.getElementById('id01').style.display='block';
// Display some data from the object:
document.getElementById("TitleModal").innerHTML = Yellow.Title;
document.getElementById("PriceModal").innerHTML = Yellow.Price;
document.getElementById("DescriptionModal").innerHTML = Yellow.Description;
}
function functionBlue() {
document.getElementById('id01').style.display='block';
// Display some data from the object:
document.getElementById("TitleModal").innerHTML = Blue.Title;
document.getElementById("PriceModal").innerHTML = Blue.Price;
document.getElementById("DescriptionModal").innerHTML = Blue.Description;
}
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div style="background-color:red; width:50px; height:50px; float: left;" id="red"></div>
<div style="background-color:blue; width:50px; height:50px; float: left;" id="blue"></div>
<div style="background-color:yellow; width:50px; height:50px; float: left;" id="yellow"></div>
<div id="id01" class="w3-modal">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">×</span>
<h2 id="TitleModal">Some text. Some text. Some text.</h2>
<h2 id="PriceModal">Some text. Some text. Some text.</h2>
<p id="DescriptionModal">Some text. Some text. Some text.</h2>
</div>
</div>
</div>
</div>
Thanks to everybody.
Is that what you expect ?
const SquareColors
= document.getElementById('ColorsChoices')
, SquareMessage
= { onRed : { Title: 'RedIsTheNewBlack', Price: '100', Description: 'This red is the best color' }
, onBlue : { Title: 'BlueIsTheNewBlack', Price: '500', Description: 'This blue is the best color' }
, onYellow : { Title: 'YellowIsTheNewBlack', Price: '900', Description: 'This yellow is the best color' }
}
, Modal_info
= document.getElementById('idModal')
;
Modal_info.show=_=>Modal_info.classList.remove('noDisplay')
Modal_info.hide=_=>Modal_info.classList.add('noDisplay')
idModal.onclick=e=>
{
if (!e.target.matches('#close-button, #idModal')) return
e.preventDefault()
Modal_info.hide()
}
const TitleModal = document.getElementById('TitleModal')
, PriceModal = document.getElementById('PriceModal')
, DescriptionModal = document.getElementById('DescriptionModal')
;
SquareColors.onclick=e=>
{
if (!e.target.matches('.colorButton')) return
let inColor = e.target.id
TitleModal.textContent = SquareMessage[inColor].Title
PriceModal.textContent = SquareMessage[inColor].Price
DescriptionModal.textContent = SquareMessage[inColor].Description
Modal_info.show()
}
nav#ColorsChoices div {
width : 50px;
height: 50px;
float : left;
}
#onRed { background-color: red }
#onBlue { background-color: blue }
#onYellow { background-color: yellow }
.noDisplay { display: none }
#idModal {
z-index: 3;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0,0,0,0.4);
}
#idModal > div {
position: relative;
display: block;
width: 30em;
margin: 5em auto;
background-color: #fff;
padding: 1em;
}
#close-button {
position: absolute;
top: 0;
right: .3em;
cursor: pointer;
font-size: 2em;
font-weight: bold;
}
#close-button:hover { color: crimson; }
<nav id="ColorsChoices">
<div class="colorButton" id="onRed"></div>
<div class="colorButton" id="onBlue"></div>
<div class="colorButton" id="onYellow"></div>
</nav>
<div id="idModal" class="noDisplay">
<div>
<span id="close-button">×</span>
<h2 id="TitleModal">Some text. </h2>
<h2 id="PriceModal">Some text. </h2>
<p id="DescriptionModal">Some text. </h2>
</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.

Jquery functions continue to apply even the CSS is changed. How do I stop this?

The fiddle first.
I have nameCards which expand and contract when clicked by adding/removing classes. Additionally, they move to different sections in the page when buttons are clicked (again by adding/removing classes). The problem: Despite them no longer having the classes needed to trigger the functions, the function still applies to them.
In the code, they move from .unmatched to .matched, so the function selector $('.matched.nameCard') should no longer work, but it does, as shown by the fact that the alert from the .click() still shows after it got moved.
I've tried event.stopProgation() basically everywhere in the functions, tried using a local variable instead of the global variable currentCard, and have double checked that the classes are changing by inspecting using .html. By my reasoning, the second they change from .unmatched to .matched the original function should stop working. Can anybody help me figure out why it's not?
Final note, the formatting got screwed up a little in the switch to fiddle, please forgive the funkyness. I tried to get rid of as much extra stuff as possible.
Edit: Changed from #matched in my question to .matched
Full code:
HTML
<div class="col-xs-3 col-sm-4 col-md-2">
<h2>Unmatched:</h2>
<div class="container-fluid matchBoxes" id="unmatched">
<div class="namesAndModals">
<div class="nameCard preClick unmatched" id="unmatchedFunctionalityShell">
<h2 class="memberName"></h2>
<div class="nameCardContents">
<button type="button" class="btn checkmark" id="yesBtn" href="#" data-toggle="modal" data-target="#pairModal">
<div class="checkmark_circle"></div>
<div class="checkmark_stem"></div>
<div class="checkmark_kick"></div>
</button>
<input type="text" placeholder="PNM ID#" class="IDnum ansField" autofocus/>
<input type="text" placeholder="Last Name" class="lastName ansField" id="lastName"/>
<input type="text" placeholder="First Name" class="firstName ansField" id="firstName"/>
</div>
</div>
<div class="nameCard preClick unmatched">
<h2 class="memberName">Jane Doe</h2>
</div>
<div class="nameCard preClick unmatched">
<h2 class="memberName">Jane Doe</h2>
</div>
<!-- Pairing Modal -->
<div id="pairModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ready to Pair?</h4>
</div>
<div class="modal-body">
<p id="pairDialog"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="pairButton" data-dismiss="modal">Pair</button>
<button type="button" class="btn btn-default" id="dismissButton" data-dismiss="modal">Never Mind</button>
</div>
</div>
</div>
</div>
</div>
</div>
<h2>Matched:</h2>
<div class="container-fluid matchBoxes" id="matched">
<div class="nameCard preClick matched">
<h2 class="memberName">Jane Doe</h2>
<div class="matchedNameCardContents">
<p class="pnmName">Jaime Doe</p>
</div>
</div>
</div>
CSS
* {
font-family: 'Gill Sans MT', 'Microsoft YaHai UI', sans-serif;
font-weight: 200;
}
#unmatched {
width: auto;
height: 300px;
background-color: rgba(211, 211, 211, .55);
border-radius: 10px;
margin: 10px 0;
overflow-y:scroll;
min-width: 270px;
}
#matched {
width: 110%;
height: 200px;
background-color: rgba(211, 211, 211, .55);
border-radius: 10px;
margin: 10px 0;
overflow-y:scroll;
min-width: 270px;
}
.nameCard {
width: 100%;
height: 70px;
background-color: rgba(255,100,171,.5);
border-radius: 10px;
display: block;
margin: 2px 1px;
overflow:auto;
}
.nameCard.preClick {
height: 30px;
}
.nameCard .nameCardContents {
display:none;
}
.nameCard h2 {
display:inline-block;
font-size: 20px;
font-weight: 500;
padding: 5px 0 3px 10px;
text-align: left;
width: 75%;
float:left;
}
.nameCard .IDnum {
display:inline-block;
margin: 5px 2px 3px 10px;
padding: 3px 0px 3px 2px;
width: 25%;
}
.nameCard .lastName {
display:inline-block;
margin: 5px 2px 3px 2px;
padding: 3px 0px 3px 2px;
width: 30%;
}
.nameCard .firstName {
display:inline-block;
margin: 5px 2px 3px 2px;
padding: 3px 0px 3px 2px;
width: 30%;
}
#unmatchedFunctionalityShell {
display:none;
}
.checkmark {
display:inline-block;
margin:auto;
margin-right:2px;
padding-right:0px;
-ms-transform: rotate(45deg); /* IE 9 */
-webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
transform: rotate(45deg);
}
.checkmark_circle {
position: absolute;
width:22px;
height:22px;
background-color: rgba(46,195,1,.8);
border-radius:11px;
left:0;
top:0;
}
.checkmark_stem {
position: absolute;
width:3px;
height:9px;
background-color:#fff;
left:11px;
top:6px;
}
.checkmark_kick {
position: absolute;
width:3px;
height:3px;
background-color:#fff;
left:8px;
top:12px;
}
#yesBtn{
display:inline-block;
background-color: rgba(46,195,1,0);
width:20px;
height:20px;
border-radius:11px;
}
/* Matched Members */
.matched.nameCard {
background-color: rgba(50, 205, 50, .5);
}
.matched p {
display: inline-block;
text-align: left;
margin-left: 10px;
padding-top: 5px;
}
.matched .btn {
display: inline-block;
background-color: rgba(255,37,37,.7);
padding: 4px;
float:right;
}
/*I had to use important here to get rid of the nameCardContents. Try and remove it later */
#matched .nameCardContents {
display:none !important;
}
#matched .preClick .matchedNameCardContents {
display:none;
}
Javascript
$(document).ready(function(){
$('.unmatched.nameCard').hover(function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
currentCard.off('click').on("click", function(event) {
// alert("hello");
//switches between "active" and "inactive (preClick)" card
$("#unmatched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.nameCardContents');
cardContents.appendTo(currentCard);
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
alert("this shouldn't happen after being moved to #matched");
} else {
cardContents.show();
alert("this shouldn't happen after being moved to #matched");
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.off('click', ".btn").on("click", ".btn", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
$("#pairDialog").text("Are you sure you want to pair " + memberName + " with " + pnmFirstName + " " + pnmLastName + "?");
});
currentCard.off('click', ".ansField").on("click", ".ansField", function(event) {
event.stopPropagation();
});
//Unmatched to Matched
$('#pairModal #pairButton').off('click').on("click", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
currentCard.removeClass('unmatched');
currentCard.addClass('matched');
currentCard.children(".nameCardContents").hide();
currentCard.append("<div class='matchedNameCardContents'><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.addClass('preClick');
currentCard.prependTo("#matched");
$("#lastName").val("");
$("#firstName").val("");
});
//Move from Unmatched to Unavailible
//Remove for one party
$('#discardModal #onePartyButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed for one party</p></div>")
newDiv.appendTo(currentCard);
});
//Remove for one round
$('#discardModal #oneRoundButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed for one round</p></div>")
newDiv.appendTo(currentCard);
});
//Remove for all recruitment
$('#discardModal #allRecruitmentButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed from recruitment</p></div>")
newDiv.appendTo(currentCard);
});
});
});
//Matched Name cards
$(document).ready(function(){
$('.matched.nameCard').off().hover(function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
var pnmName = $(this).children(".pnmName").text();
currentCard.on("click", function(event) {
//switches between "active" and "inactive (preClick)" card
//$("#matched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.matchedNameCardContents');
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
} else {
cardContents.show();
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.on("click", ".btn", function(event) {
$("#unpairButton").text("Are you sure you want to unpair " + memberName + " and " + pnmName + "?");
});
currentCard.on("click", ".ansField", function(event) {
event.stopPropagation();
});
//.unbind() is the best thing to happen to me
//Unmatched to Matched
$('#pairModal #pairButton').unbind('click').on("click", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
currentCard.removeClass('unmatched');
currentCard.addClass('matched');
currentCard.children(".nameCardContents").hide();
var addPNM = $("<div class='matchedNameCardContents'><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.append("<div><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.prependTo("#matched");
});
});
});
I figured it out! I looked into event delegation based on the comments and changed everything to take that into account. Here's a preview of what my new functions look like:
$(document).ready(function(){
$('#unmatched').off().on("mouseover", ".unmatched.nameCard", function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
currentCard.off('click').on("click", function() {
//switches between "active" and "inactive (preClick)" card
$("#unmatched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.nameCardContents');
cardContents.appendTo(currentCard);
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
} else {
cardContents.show();
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.off('click', ".btn").on("click", ".btn", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
$("#pairDialog").text("Are you sure you want to pair " + memberName + " with " + pnmFirstName + " " + pnmLastName + "?");
$("#removeMember").text("How long do you want to remove " + memberName + " from recruitment?");
});
});
});

Why does my application keep running?

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)

Categories