.click only if div contains 2 specific divs - javascript

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.

Related

how to fix onClick button for append functions?

Here I work on a project where I want to implement open and close buttons but I am not able to do
currently, it's a close button for both, I need to add separate open and close buttons so that when the user clicks on open then it's open and when someones click on close then it should close properly also when I click continuously close then buttons freezes for sometime
Here is the demo of my JSFiddle Demo
please check the js Fiddle demo where buttons doesn't work properly
Here is the code
function createItem(item) {
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
newItem.appendTo('.item-append');
}
function countSaveItems() {
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test_' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
$(this).append(`<button class='close'>Close</button>`);
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
countSaveItems();
}
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0) {
existing.remove();
} else {
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
localStorage.removeItem(`test_${id}`);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(this).parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<div class='item-append'>
</div>
<div class='count'>0</div>
Any Kind of help or suggestion is highly appreciated
To do the effect you need to add the open button into the HTML because that will be static, then switch between "Open" and "Close" when the user clicks into the "Open" or close the item, also needs to fix the local storage instead of removing in the close button just switch the value to false and validate based on that value. check the following code to see if that is what you are looking for:
function createItem(item){
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
clonedItem.children('.open').remove();
clonedItem.append(`<button class='close'>Close</button>`);
newItem.appendTo('.item-append');
}
function countSaveItems(){
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
var id = $(this).data("id");
var lsId = `test_${id}`;
$(this).toggleClass('productad');
if (!$(this).hasClass('productad')){
window.localStorage.setItem(lsId, false);
$(this).children(".open").html("Open");
createItem($(this));
}else{
window.localStorage.setItem(lsId, true);
$(this).children(".open").html("Close");
$(`.item-append div[data-id='${id}']`).remove();
}
countSaveItems();
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
}
countSaveItems();
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0){
existing.remove();
}else{
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
window.localStorage.setItem(`test_${id}`, false);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(`.item-save[data-id='${id}']`).children(".open").html("Open");
$(this).parent().parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='124'>
Save2 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='125'>
Save3 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='126'>
Save4 <button class='open'>Open</button>
</div>
</div>
<div class='item-append'></div>
<div class='count'>0</div>

Delete elements below some element using jQuery

I've next code:
$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container', 'element-2');
});
function deleteElementsBelow(parentContainerSelector, deleteBelowSelector) {
var deleteOthers = false;
$(parentContainerSelector).children().each(function () {
var $elem = $(this);
if (deleteOthers) {
$elem.remove();
} else if ($elem.hasClass(deleteBelowSelector)) {
deleteOthers = true;
}
});
}
});
#parent-container div {
background-color: red;
width: 20px;
height: 20px;
margin: 10px;
}
#parent-container div:nth-child(2n) {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-container">
<div class="element-1"></div>
<div class="element-2"></div>
<div class="element-3"></div>
<div class="element-4"></div>
<button id="delete-button" type="button">Delete</button>
</div>
Is it possible to do action deleteElementsBelow by native jQuery API?
You could use something like $(parentContainerSelector + " ." +deleteBelowSelector).nextAll("div").remove() to remove all div after the target element.
This will remove divs with class element-3 and element-4
$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container', 'element-2');
});
function deleteElementsBelow(parentContainerSelector, deleteBelowSelector) {
var deleteOthers = false;
$(parentContainerSelector + " ." +deleteBelowSelector).nextAll("div").remove()
}
});
#parent-container div {
background-color: red;
width: 20px;
height: 20px;
margin: 10px;
}
#parent-container div:nth-child(2n) {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-container">
<div class="element-1"></div>
<div class="element-2"></div>
<div class="element-3"></div>
<div class="element-4"></div>
<button id="delete-button" type="button">Delete</button>
</div>

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?");
});
});
});

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/

Counting variable in JS that has been parsed from php

I got a variable that represents required number of items and counting of dropped items inside droppable area. You can view example here. So what I want is to pass a variable to javascript and then calculate the difference.
I put my variable into div:
<div id="numbr" >10</div>
And here is the js code which counts dropped items and displays the total:
var n = $(this).closest("div.proc").find(".dropClass").length -1;
$(this).closest("div.proc").find("div.dropped").text("Items Dropped: " + n + ".");
My goal is to find differences between <div class="numbr"> and n, and then display it. How can I achieve this in js?
It is just an example.In my system, the number is a php variable received from user's input. There could be more than 2 boxes: it depends on user's input.
Try the following in both the drop event and the click event:
var proc = $(this).closest("div.proc");
proc.find('.dif').text('Difference ' +(proc.find('.numbr').text() - n));
demo: https://jsfiddle.net/d1ddsj8m/2/
var itm = [];
$("#savebutton").click(function() {
LISTOBJ.saveList();
});
$("#myAccordion").accordion({
heightStyle: "content",
active: false,
collapsible: true
});
$("#myAccordion li").draggable({
appendTo: "body",
helper: "clone",
start: function(ev, ui) {
ui.helper.width($(this).width());
}
});
$(".projLeader ol").droppable({
tolerance: 'pointer',
hoverClass: 'highlight',
drop: function(ev, ui) {
var zz = ui.draggable.text()
var xyz = itm.includes(zz);
if (xyz === false) {
var item = ui.draggable;
if (!ui.draggable.closest('.placeholder').length) item = item.clone().draggable(); // if item was dragged from the source list - clone it
//this.innerHTML = ''; // clean the placeholder
item.addClass('dropClass').appendTo(this);
// append item to placeholder
//add to array
itm.push(zz);
var n = $(this).closest("div.proc").find(".dropClass").length;
$(this).closest("div.proc").find(".dropped").text("Items Dropped: " + n + ".");
$(this).closest("div.proc").find('.dif').text('Difference ' + ($(this).closest("div.proc").find('.numbr').text() - n));
} else {
alert('Name is Already Exist');
}
}
});
$(".projLeader").on('click', '.closer', function() {
var item = $(this).closest('.item');
var element = $("#myAccordion ul li").filter(function() {
return $(this).text() == item.text();
});
itm.splice(item);
var n = $(this).closest("div.proc").find(".dropClass").length - 1;
$(this).closest("div.proc").find("div.dropped").text("Items Dropped: " + n + ".");
$(this).closest("div.proc").find('.dif').text('Difference ' + ($(this).closest("div.proc").find('.numbr').text() - n));
item.fadeTo(200, 0, function() {
item.remove();
})
});
var LISTOBJ = {
saveList: function() {
var listCSV = "";
$(".projLeader li").each(function() {
if (listCSV === "") {
listCSV = $(this).text();
} else {
listCSV += ", " + $(this).text();
}
$("#output").text(listCSV);
$(".hiddenListInput").val(listCSV);
});
}
}
body {
font-family: verdana;
font-size: 12px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
margin-bottom: 10px;
}
ol {
list-style-type: none;
}
.item {
height: 20px;
width: 180px;
margin: 5px;
padding: 5px;
border: 1px solid gray;
background-color: #cd8;
position: relative;
}
.item .closer {
position: absolute;
right: 5px;
top: 2px;
font: bold 14px arial;
color: #666;
padding: 1px 3px;
line-height: 1;
cursor: pointer;
display: none;
}
.item .closer:hover {
color: #000;
}
.placeholder {
height: 30px;
width: 195px;
margin: 5px;
background: #eee;
border: 1px dashed #999;
}
.placeholder .item {
margin: 0;
}
ol .item .closer {
display: block;
}
.highlight {
border: 1px solid red;
background: #fff;
}
.highlight .item {
opacity: 0.3;
}
.ui-draggable-dragging {
z-index: 99;
opacity: 1 !important;
}
.dropClass {
background-color: lightblue;
padding-left: 10px;
width: 180px;
border: 1px solid black;
border-radius: 8px;
margin-bottom: 5px;
}
.dropped {
display: inline;
}
.dif {
display: inline;
}
.numbr {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
<h1 class="ui-widget-header">Products</h1>
<div id="myAccordion">
<h3>T-Shirts</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>Lolcat Shirt</li>
<li class="item"><span class="closer">x</span>Cheezeburger Shirt</li>
<li class="item"><span class="closer">x</span>Buckit Shirt</li>
</ul>
</div>
<h3>Bags</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>Zebra Striped</li>
<li class="item"><span class="closer">x</span>Black Leather</li>
<li class="item"><span class="closer">x</span>Alligator Leather</li>
</ul>
</div>
<h3>Gadgets</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>iPhone</li>
<li class="item"><span class="closer">x</span>iPod</li>
<li class="item"><span class="closer">x</span>iPad</li>
</ul>
</div>
</div>
<div class='proc'><pre>
<br /></pre>
<div class="projLeader">
<label>Box1. Required number:
<div class="numbr">10</div>.
<div class="dropped"></div>
<div class="dif">Difference:</div>
</label>
<div class="ui-widget-content">
<ol>
<li class="placeholder" name="projLeader"></li>
<input type="hidden" name="projLeader" class="hiddenListInput1" />
</ol>
</div>
</div>
</div>
<div class='proc'><pre>
<br /></pre>
<div class="projLeader">
<label>Box2. Required number:
<div class="numbr">5</div>.
<div class="dropped"></div>
<div class="dif">Difference:</div>
</label>
<div class="ui-widget-content">
<ol>
<li class="placeholder" name="projLeader"></li>
<input type="hidden" name="projLeader" class="hiddenListInput1" />
</ol>
</div>
</div>
</div>
<br/>
<input type="submit" id="savebutton" class="button" value="Save" onclick="userSubmitted = true;" />
<div id="output"></div>
It looks like you are using jQuery, which makes it really easy to manipulate the DOM dynamically.
Here is what I would do. First, add a difference div which will hold the difference of n and numbr:
<div id="numbr">10</div>
<div id="difference"></div>
And in your JS, calculate the difference and add it to the div:
var n = $(this).closest("div.proc").find(".dropClass").length - 1;
var difference = parseInt($('#numbr').text(), 10) - n;
if (difference >= 0) {
$('#difference').text('Difference ' + difference);
}
Do you mean that you can use a PHP variable in javascript. If that's the case, this is probably what you are looking for:
<?php
$myVariable = 200;
?>
<script type="text/javascript">
$(document).ready(function () {
var myvar = <?= $myVariable; ?>;
$(document).on('change', '.numbr', function () {
var number = parseInt($(this).text(), 10);
var difference = myvar - number;
$('.somediv').text($difference);
});
});
</script>
<div class="numbr">20</div>
To get the dropClass content, use the text() method. length will give you the number of nodes for the given selector, it's not what you want here.
You can get the numbr and dropClass content with the text() method.
Try this(added some html for the snippet to work):
inner = $('#innerproc').closest("div.proc");
numbr = $('#numbr').text();
n = inner.find(".dropClass").text();
inner.find("div.dropped").text("Items Dropped: " + (n - numbr) + ".");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="numbr">10</div>
<div class="proc">
<div id="innerproc"></div>
<div class="dropClass">21</div>
<div class="dropped"></div>
</div>

Categories