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>
Related
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>
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.
I create a clone function with jquery and included a deleted button inside it, when i click the delete button it will delete the particular box parent and hide the delete button when the delete button length < 2, i generate unique id for each box start from 1, it work when i delete the box with id in sequence start from 3,2,1 and 4 (from bottom to top box), but the delete button can't hide when i start delete start from 4,1,2,3 (from the top to the bottom), here my code below
$(document).ready(function(){
var counter = 1;
var total = 1;
var el = $('#clone');
var box = $('.box');
var container = '.container';
var deleteBtn = $('#delete');
$(document.body).on('click','#clone', function(){
counter ++;
total ++;
var startClone = box.clone(true);
startClone.appendTo(container);
box.attr('id','hallo' + counter);
$('.box').find('#delete').show();
deleteBtn.show();
})
$('#delete').on('click', function(){
total --;
$(this).closest('.box').remove();
console.log(total);
if(total < 2){
deleteBtn.hide();
}else {
deleteBtn.show();
}
})
})
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
#delete {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div class="container">
<div class="box" id="hallo1">
<button id="delete">Delete</button>
</div>
</div>
<button id='clone'>Clone this</button>
</body>
</html>
id should be unique. When you clode box element there would be multiple buttons with id delete and will create issues.
I used class .delete. Please check.
$(document).ready(function() {
var counter = 1;
var el = $('#clone');
var box = $('#hallo1');
var container = '.container';
box.hide(); //Hide the orginal box
var clone = function(){
counter++;
var startClone = box.clone(true);
startClone.append(counter - 1); //For test purposes. Please remove
startClone.appendTo(container);
startClone.attr('id', 'hallo' + counter);
startClone.show(); //Show the cloned box
startClone.find('.delete').show();
toggleDelete();
}
var toggleDelete = function(){
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
}
clone();//Clone initaly
$(document.body).on('click', '#clone', function() {
clone();
})
$('.delete').on('click', function() {
$(this).closest('.box').remove();
toggleDelete();
})
})
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
.delete {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box" id="hallo1">
<button class="delete">Delete</button>
</div>
</div>
<button id='clone'>Clone this</button>
Alternative cleaner Approach:
$(document).ready(function() {
$("#clone").click(function() {
clone();
toggleDelete();
});
$("body").on('click', '.delete', function() {
$(this).closest('.box').remove();
toggleDelete();
})
var toggleDelete = function() {
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
}
var clone = function() {
$("#container").append('<div class="container"><div class="box"><button class="delete">Delete</button></div></div>');
}
clone(); //Call init
});
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
.delete {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
<button id='clone'>Clone this</button>
Identifiers must be unique so assign a CSS then Class Selector can be used to target the element and You should use Event delegation to bind event with dynamic elements.
container.on('click', '.delete', function () {
$(this).closest('.box').remove();
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
});
$(document).ready(function() {
var el = $('#clone');
var box = $('.box');
var container = $('.container');
$(document.body).on('click', '#clone', function() {
var startClone = box.eq(0).clone();
startClone.appendTo(container);
$('.box').find('.delete').show();
})
container.on('click', '.delete', function() {
$(this).closest('.box').remove();
if ($(".delete").length < 2) {
$(".delete").hide();
} else {
$(".delete").show();
}
})
})
.box {
background: red;
width: 100px;
height: 100px;
margin: 5px 0;
}
#clone {
display: block;
}
.delete {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box" id="hallo1">
<button class="delete">Delete</button>
</div>
</div>
<button id='clone'>Clone this</button>
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/
I'm working on my first serious website and i'm stuck on this problem.
First of all I think my JQuery is extremly clumsy and could probably have been done in a more efficient way, would love some help on how to code this better (Feks i probably use to many functions).
Secoundly I need some help with the animation. I want the divs to animate over to the leftside off the container before they open. The way it is now looks so unnatural.
I would appreciate any help.
http://jsfiddle.net/Skaadel/nt8a29gm/1/
HTML
<div class="container">
<div class="row">
<div class="test1 col-sm-3">
<div id="boks1">About Me</div>
</div>
<div class="test2 col-sm-3">
<div id="boks2">Portfolio</div>
</div>
<div class="test3 col-sm-3">
<div id="boks3">Project</div>
</div>
<div class="test4 col-sm-3">
<div id="boks4">TEST</div>
</div>
</div>
</div>
CSS
html {
width: 100%;
}
#test {
background-color: blue;
height: 400px;
width: 400px;
margin: auto;
}
#wrapper {
height: 500px;
}
.container {
background-color: black!important;
margin-bottom: 40px!important;
}
#boks1 {
height: 400px;
width: 100px;
background-color: red;
position: relative;
z-index: 15;
}
#boks2 {
height: 400px;
width: 100px;
background-color: blue;
}
#boks3 {
height: 400px;
width: 100px;
background-color: white;
}
#boks4 {
height: 400px;
width: 100px;
background-color: pink;
}
JQUERY
$(document).ready(function () {
$("#boks1").click(function () {
if ($("#boks1").width() == 100) {
$("#boks1").animate({
width: "720px"
});
$("#boks2").css("display", "none");
$("#boks3").css("display", "none");
$("#boks4").css("display", "none");
} else {
$("#boks1").animate({
width: "100px"
});
$("#boks2").css("display", "");
$("#boks3").css("display", "");
$("#boks4").css("display", "");
}
});
});
$(document).ready(function () {
$("#boks2").click(function () {
if ($("#boks2").width() == 100) {
$("#boks2").animate({
width: "720px"
});
$(".test1").css("display", "none");
$(".test4").css("display", "none");
$(".test3").css("display", "none");
} else {
$("#boks2").animate({
width: "100px"
});
$(".test1").css("display", "");
$(".test4").css("display", "");
$(".test3").css("display", "");
}
});
});
$(document).ready(function () {
$("#boks3").click(function () {
if ($("#boks3").width() == 100) {
$("#boks3").animate({
width: "720px"
});
$(".test1").css("display", "none");
$(".test2").css("display", "none");
$(".test4").css("display", "none");
} else {
$("#boks3").animate({
width: "100px"
});
$(".test1").css("display", "");
$(".test2").css("display", "");
$(".test4").css("display", "");
}
});
});
$(document).ready(function () {
$("#boks4").click(function () {
if ($("#boks4").width() == 100) {
$("#boks4").animate({
width: "720px"
});
$(".test1").css("display", "none");
$(".test2").css("display", "none");
$(".test3").css("display", "none");
} else {
$("#boks4").animate({
width: "100px"
});
$(".test1").css("display", "");
$(".test2").css("display", "");
$(".test3").css("display", "");
}
});
});
I have changed your code somewhat. Changes are as follows:
1) In your HTML added class name boks class="boks" along your inner Div.
2) In your CSS added properties for .boks, #boks1-2-3-4 and .col-sm-3. Also Added class .zindex
3) In your JQuery i changed everything. Have a look and ask if you stuck anywhere.
Working : Demo
JQuery
$(document).ready(function() {
$(".boks").click(function() {
var curId = this.id; //Gives you id of clicked element.
var curWidth = $("#" + curId).width(); // Taking width to check if it's 100px.
var offset = $("#" + curId).offset(); // Taking Position for animating to left.
var leftPos = offset.left;
var firstElementLeftPos = $("#boks1").offset().left;
leftPos = leftPos - firstElementLeftPos;
if (curWidth == 100) {
$(this).parent(".col-sm-3").css('left', '-' + leftPos + 'px');
$("#" + curId).css("width", "720px").addClass('zindex');
} else {
$(this).parent(".col-sm-3").css('left', '0px');
$("#" + curId).css("width", "100px").delay(500).queue(function() {
$("#" + curId).removeClass('zindex');
});
}
});
});
CSS
html {
width: 100%;
}
#test {
background-color: blue;
height: 400px;
width: 400px;
margin: auto;
}
#wrapper {
height: 500px;
}
.container {
background-color: black!important;
margin-bottom: 40px!important;
}
/* Edits are to Below CSS */
.boks {
height: 400px;
width: 100px;
position: relative;
overflow: hidden;
transition: all 0.5s ease-in-out;
}
#boks1 {
background-color: red;
}
#boks2 {
background-color: blue;
}
#boks3 {
position: relative;
background-color: white;
}
#boks4 {
background-color: pink;
}
.col-sm-3 {
left: 0px;
transition: 0.5s ease-in-out;
position: relative;
}
.zindex {
z-index: 999;
}
HTML
<div class="row">
<div class="test1 col-sm-3">
<div class="boks" id="boks1">About Me</div>
</div>
<div class="test2 col-sm-3">
<div class="boks" id="boks2">Portfolio</div>
</div>
<div class="test3 col-sm-3">
<div class="boks" id="boks3">Project</div>
</div>
<div class="test4 col-sm-3">
<div class="boks" id="boks4">TEST</div>
</div>
</div>
</div>
just to show you how you could reduce your code with using $(this) and class names in jQuery ...
http://jsfiddle.net/nt8a29gm/3/
$(document).ready(function () {
$(".box").click(function () { // check for click on .box
if($(this).width() == 100) { // if this one width is 100
$('.box').not(this).hide(); // hide all but this
$(this).animate({ // animate the one we clicked on
width: "720px"
});
} else {
$(this).animate({ // make this one small again
width: "100px"
}, 900, function() { // 900 is animation speed
// Animation complete. // wait this animation is finished
$('.box').not(this).show(); // show all boxes again
});
}
});
});
HTML see class="box"
<div class="container">
<div class="row">
<div class="test1 col-sm-3">
<div class="box">About Me</div>
</div>
<div class="test2 col-sm-3">
<div class="box">Portfolio</div>
</div>
<div class="test3 col-sm-3">
<div class="box">Project</div>
</div>
<div class="test4 col-sm-3">
<div class="box">TEST</div>
</div>
</div>
</div>