Trouble Removing One Child DIV At A Time - javascript

I am building a simple Grocery List App and I am having issues trying to remove a place holder div element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Grocery List App</title>
<link type="text/css" href="style/form.css" rel="stylesheet"/>
</head>
<body>
<div id="container">
<div id="left_side">
<div id="to_buy">To Buy:</div>
</div>
<div id="right_side">
<div id="in_cart">In Cart:</div>
</div>
</div>
<input type="text" id="item_body" placeholder="Type Item to Add">
<script src="scripts/jquery-1.11.2.min.js"></script>
<script src="scripts/grocery.js"></script>
<script src="scripts/jquery-ui/jquery-ui.js"></script>
</body>
</html>
JS
$(function () {
var rmv = false;
$('#item_body').keydown(function(e) {
if (e.keyCode == 13) {
var add = $('#item_body').val();
$("#to_buy").append('<div class="draggable_item">' + add + '</div>');
$("#in_cart").append('<div class="holder"></div>');
}
$(".draggable_item").draggable( {
axis: "x"
});
$(".draggable_item").dblclick(function() {
this.remove();
$('#in_cart > div:first').remove();
});
});
});
CSS
#to_buy {
float:left;
width: 50%;
height: 100%;
color: #00E5EE;
}
#in_cart {
float: left;
width: 49%;
height: 100%;
color: #00E5EE;
}
#container {
width:100%;
height: 100%;
}
#left_side {
height: 100%;
width: 50%;
float:left;
background: #5D5851;
}
#right_side {
height: 100%;
width: 50%;
float: left;
background: #6D5D4D;
}
#item_body {
float:left;
clear:both;
color: #326B62;
}
body {
background: #B1ADA5;
}
.draggable_item {
color: #FFF;
}
.holder {
height: 20px;
}
So the screen is split vertically between "to_buy" and "in_cart." When I add an item to "to_buy" I also add a "dummy" div to "in_cart" so that the two sides remain even. However, when I double click to remove an item, when
$('#in_cart > div:first').remove();
gets called, first one div is removed, then on the next double click two, then four etc etc. Apparently, it is getting called multiple times or something else wonky is going wrong.

This is because you bind event handlers for double click event on every Enter key press so they multiply on every item addition. Just move dblclick registration outside:
var rmv = false;
$('#item_body').keydown(function (e) {
if (e.keyCode == 13) {
var add = $('#item_body').val();
$("#to_buy").append('<div class="draggable_item">' + add + '</div>');
$("#in_cart").append('<div class="holder"></div>');
}
$(".draggable_item").draggable({
axis: "x"
});
});
$("#left_side").on("dblclick", ".draggable_item", function () {
this.remove();
$('#in_cart > div:first').remove();
});
Also note, that it makes sense to delegate double click event to the parent container #left_side so you don't have to worry about presence of elements at the time of event registration.
Here is a demo: http://jsfiddle.net/hx11gkcj/

Related

fadeToggle on body click

I have this div which shows/hides with display:none/block by clicking on an id #cart. The div opens and closes by clicking on element with the id but I want to close the div on body click too. How can I do it please?
Code I am using is below:
jQuery("#cart").on("click", function() {
jQuery(".shopping-cart").fadeToggle( "fast");
});
jQuery("#cart, body").on("click", function() {
jQuery(".shopping-cart").fadeToggle("fast");
});
What you can do is add a listener to the entire window and check for clicks. When there is a click, we check which element has been clicked and check on whether it's the element. We repeat this for the parent element as well.
<!DOCTYPE html>
<html>
<head>
<script>
function checkClickOutsiteElement(clickedElement, elementToCheck){
var iterator = clickedElement;
while(true){
// The click was in the element.
if( iterator === elementToCheck )
return;
// Go to the parent.
if( !iterator.parentElement ){
alert('outside menu');
return;
}
iterator = iterator.parentElement;
}
}
window.addEventListener('click', function(event){
checkClickOutsiteElement(event.target, document.getElementById('menu'));
});
</script>
</head>
<body>
<div class="wrapper">
<div id="menu" style="width: 100px; height: 100px; background-color: red;"></div>
</div>
<div class="wrapper">
<div id="not_menu" style="width: 100px; height: 100px; background-color: green;"></div>
</div>
</body>
</html>
You probably want two separate functions, since your cart button should toggle both ways, but the body click handler should only toggle out.
Protip: on() isn't doing anything for you that click() wouldn't, the way you're using it. The latter is a bit cleaner.
jQuery("#cart").click(function() {
jQuery(".shopping-cart").fadeToggle("fast");
});
jQuery("body").click(function() {
jQuery(".shopping-cart").fadeOut("fast");
});
Protip 2: Easily and safely alias jQuery to $ like so:
jQuery(function($) { // document ready with dollar alias
$("#cart").click(function() {
...
});
I have this div which shows/hides with display:none/block by clicking
on an id #cart. The div opens and closes by clicking on element with
the id but I want to close the div on body click too.
In vanilla javascript, you can:
write a function to show / hide the div
add a click event listener to #cart
add a click event listener to body
Working Example:
// Grab #cart
const cart = document.getElementById('cart');
// Grab .myDiv
const myDiv = document.getElementsByClassName('div')[0];
// Function to toggle .myDiv
const toggleMyDiv = (e) => {
if (e.target === e.currentTarget) {
myDiv.dataset.display = (myDiv.dataset.display === 'show') ? 'hide' : 'show';
}
}
// Add Click Event Listener to #cart
cart.addEventListener('click', toggleMyDiv, false);
document.body.addEventListener('click', toggleMyDiv, false);
body,
#cart {
cursor: pointer;
}
div {
display: inline-block;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
font-weight: bold;
}
#cart {
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
.div {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
}
.div[data-display="show"] {
opacity: 1;
}
.div[data-display="hide"] {
opacity: 0;
}
<div id="cart">Cart</div>
<div class="div show" data-display="show">myDiv</div>

Jquery: How to hide an element while it is in orther element?

how to hide a "cube-2" by click on "click-me" that its included by "cube-2"?
I made an event but it deleted all of my cube-2, I want to hide cube-2 one by one. Anyone can solve this? please help me.
$('.cube-1').click(function name(params) {
$('.cube-1').append('<div class="cube-2"><div class="click-me">click me to hide this cube</div></div>');
// how to add event click on "click-me" to hide "cube-2"??
})
.cube-1 {
width: 100px;
height: 100px;
float: left;
background: blue;
}
.cube-2 {
margin-left: 100px;
width: 100px;
height: 100px;
float: left;
background: red;
}
.click-me {
width: 100%;
height: 50px;
background: white;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
</head>
<div class="cube-1"></div>
</html>
You can add an id to your cube-2 div and it's corresponding click-me anchor tag and remove only the div with that Id.
You may also want to check Template string
$('.cube-1').click(function name(e) {
var cubeCounter = 1;
if (e.target.className == "cube-1") {
$('.cube-1').append(`<div class=cube-2 id=cube-${cubeCounter}><div class=click-me id=${cubeCounter}>click me to hide this cube</div></div>`);
cubeCounter++;
}
})
$(document).on('click', '.click-me', function name(e) {
var cubeId = e.target.id;
$(`#cube-${cubeId}`).remove();
})
you need to handle dyanamic click event of second cube and prevent click event of parent control, when child cube is clicked
$('.cube-1').click(function name(e) {
if(e.target.className == "cube-1")
{
$('.cube-1').append('<div class="cube-2"><div class="click-me">click me to
hide this cube</div></div>');
}
});
$(document).on('click','.cube-2',function name(e)
{
$(this).remove();
// how to add event click on "click-me" to hide "cube-2"??
})
Please check working demo [Link]
https://jsfiddle.net/2L3k5hcb/
You just need to bind your click on div while you appending your cube-2.
Add your script as below-
$('.cube-1').on('click',function(event){
$('.cube-1').append('click me to hide this cube');
})
function myFunction(param) {
event.stopPropagation();
$(param).remove();
}
you can use below method for dynamicly generated elements.
$(document).on('click', '.click-me', function (e) {
$(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this
$(document.body).on('click', '.cube-2', function (event) {
$(this).hide();
});
$('.cube-1').click(function(event) {
if(event.target.className =='cube-1')
$('.cube-1').append('<div class="cube-2"><div class="click-me">click me to hide this cube</div></div>');
// how to add event click on "click-me" to hide "cube-2"??
})
.cube-1 {
width: 100px;
height: 100px;
float: left;
background: blue;
}
.cube-2 {
margin-left: 100px;
width: 100px;
height: 100px;
float: left;
background: red;
}
.click-me {
width: 100%;
height: 50px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cube-1"></div>

How do i reset my cat to the original size it was

var click = 10;
$(document).ready(function() {
// nav bar event listeners set up
$('.navDiv').mouseenter(mouseEnterButton);
$('.navDiv').mouseleave(mouseLeaveButton);
//TODO add your code below to attach event listeners to the buttons
// We did the first one for you. You can use the `.click()` function or
// the .on('click') like we did below.
$('#fadeDiv').on('click', fadeCat());
$('#fadeDiv').on('click', hideCat());
$('#fadeDiv').on('click', animateCat());
$('#fadeDiv').on('click', resetCat());
});
// nav bar function to fade when mouse enters button
function mouseEnterButton() {
console.log('enter');
$(this).fadeTo('fast', 0.5);
}
// nav bar function to fade when mouse enters button
function mouseLeaveButton() {
console.log('leave');
$(this).fadeTo('fast', 1);
}
// fadeCat is a function to fade cat in or out when that button is clicked
function fadeCat(e, complete) { // ignore e, use complete as the last argument to any jQuery fade functions
//TODO your function code here
// toggle catImg fade
// append '<p>fade toggle</p>' to 'clickList'
$("#fadeDiv").click(function() {
$("#catImg").fadeToggle('fast', "linear");
$("#clickList").append('<p>fade toggle</p>');
});
}
// hideCat is a function to hide and show the cat image when that button is clicked
function hideCat() {
//TODO your function code here
// hide catImg
// append '<p>hide toggle</p>' to 'clickList
$("#hideDiv").click(function() {
$("#catImg").toggle('slow');
$("#clickList").append('<p>hide toggle</p>');
});
}
// animateCat is a function to grow the cat's height and width by 10px when that button is clicked
function animateCat(e, complete) { // ignore e, use complete as the last argument to the jQuery animate function
//TODO your function code here
// animate catImg
// append '<p>animate</p>' to 'clickList'
$('#animateDiv').click(function () {
$('#catImg').animate({
height:'+= 10px',
width:'+=10px'
});
$("#clickList").append("<p>animate</p>");
});
}
// Hard Mode
// resetCat is a function to reset the cat photo to its original size
// when that button is clicked.
function resetCat() {
// reset catImg
// append '<p>reset</p>' to 'clickList'
$('#resetDiv').click(function () {
$('#catImg').animate({
height:'-= 10px' ,
width:'-=10px'//solution for now untill i find out how to make it work
});
$("#clickList").append("<p>reset</p>");
});
}
body {
font-family: Verdana, Arial, Sans-Serif;
}
.navDiv {
height: 30px;
width: 120px;
border-radius: 5px;
padding-top: 10px;
margin: 5px;
text-align: center;
color: #FFFFFF;
background-color: #69D2E7;
font-family: Verdana, Arial, Sans-Serif;
display: inline-block;
}
#outPut {
height: 200px;
width: 400px;
}
img {
margin-left: auto;
margin-right: auto;
}
<!DOCTYPE html>
<html>
<head>
<title>Assignment 6-2</title>
<link href='styles.css' rel='stylesheet' type='text/css'/>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" charset="utf-8"></script>
<script src='script.js' type='text/javascript' ></script>
</head>
<body>
<h1>Burrito Cat</h1>
<div class="navDiv" id="fadeDiv">Fade Me!</div>
<div class="navDiv" id="hideDiv">Hide Me!</div>
<div class="navDiv" id="animateDiv">Animate Me!</div>
<div class="navDiv" id="resetDiv">Reset Me!</div>
<div id="outPut">
<img id="catImg" src="imgs/burrito-cat.png" alt="burrito cat">
</div>
<div id="clickList">
</div>
</body>
</html>
How do I make the image resize to the correct size? (I don't know how to put in the cat picture.)
You can read in the original height and width after the image loads, and either just keep it in a variable or assign it as a data- attribute to the element.
Here's an example.
$(window).on("load", function() {
var $cat = $("#catImg"),
height = $cat.height(),
width = $cat.width();
$cat.on("click", function() {
if ($(this).hasClass("big")) {
$(this).animate(
{
height: height,
width: width
},
500
);
} else {
$(this).animate(
{
height: "+=10px",
width: "+=10px"
},
500
);
}
$(this).toggleClass("big");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="catImg" src="https://d4n5pyzr6ibrc.cloudfront.net/media/27FB7F0C-9885-42A6-9E0C19C35242B5AC/4785B1C2-8734-405D-96DC23A6A32F256B/thul-90efb785-97af-5e51-94cf-503fc81b6940.jpg?response-content-disposition=inline">
find the height and width of img first, then reset to it:
var click = 10;
var imgHeight;
var imgHeight;
$(document).ready(function() {
imgHeight = $('#catImg').height();
imgWidth = $('#catImg').width();
// nav bar event listeners set up
$('.navDiv').mouseenter(mouseEnterButton);
$('.navDiv').mouseleave(mouseLeaveButton);
//TODO add your code below to attach event listeners to the buttons
// We did the first one for you. You can use the `.click()` function or
// the .on('click') like we did below.
$('#fadeDiv').on('click', fadeCat());
$('#fadeDiv').on('click', hideCat());
$('#fadeDiv').on('click', animateCat());
$('#fadeDiv').on('click', resetCat());
});
// nav bar function to fade when mouse enters button
function mouseEnterButton() {
console.log('enter');
$(this).fadeTo('fast', 0.5);
}
// nav bar function to fade when mouse enters button
function mouseLeaveButton() {
console.log('leave');
$(this).fadeTo('fast', 1);
}
// fadeCat is a function to fade cat in or out when that button is clicked
function fadeCat(e, complete) { // ignore e, use complete as the last argument to any jQuery fade functions
//TODO your function code here
// toggle catImg fade
// append '<p>fade toggle</p>' to 'clickList'
$("#fadeDiv").click(function() {
$("#catImg").fadeToggle('fast', "linear");
$("#clickList").append('<p>fade toggle</p>');
});
}
// hideCat is a function to hide and show the cat image when that button is clicked
function hideCat() {
//TODO your function code here
// hide catImg
// append '<p>hide toggle</p>' to 'clickList
$("#hideDiv").click(function() {
$("#catImg").toggle('slow');
$("#clickList").append('<p>hide toggle</p>');
});
}
// animateCat is a function to grow the cat's height and width by 10px when that button is clicked
function animateCat(e, complete) { // ignore e, use complete as the last argument to the jQuery animate function
//TODO your function code here
// animate catImg
// append '<p>animate</p>' to 'clickList'
$('#animateDiv').click(function () {
$('#catImg').animate({
height:'+= 10px',
width:'+=10px'
});
$("#clickList").append("<p>animate</p>");
});
}
// Hard Mode
// resetCat is a function to reset the cat photo to its original size
// when that button is clicked.
function resetCat() {
// reset catImg
// append '<p>reset</p>' to 'clickList'
$('#resetDiv').click(function () {
$('#catImg').animate({
height: imgHeight,
width: imgWidth//solution for now untill i find out how to make it work
});
$("#clickList").append("<p>reset</p>");
});
}
body {
font-family: Verdana, Arial, Sans-Serif;
}
.navDiv {
height: 30px;
width: 120px;
border-radius: 5px;
padding-top: 10px;
margin: 5px;
text-align: center;
color: #FFFFFF;
background-color: #69D2E7;
font-family: Verdana, Arial, Sans-Serif;
display: inline-block;
}
#outPut {
height: 200px;
width: 400px;
}
img {
margin-left: auto;
margin-right: auto;
}
<!DOCTYPE html>
<html>
<head>
<title>Assignment 6-2</title>
<link href='styles.css' rel='stylesheet' type='text/css'/>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" charset="utf-8"></script>
<script src='script.js' type='text/javascript' ></script>
</head>
<body>
<h1>Burrito Cat</h1>
<div class="navDiv" id="fadeDiv">Fade Me!</div>
<div class="navDiv" id="hideDiv">Hide Me!</div>
<div class="navDiv" id="animateDiv">Animate Me!</div>
<div class="navDiv" id="resetDiv">Reset Me!</div>
<div id="outPut">
<img id="catImg" src="imgs/burrito-cat.png" alt="burrito cat">
</div>
<div id="clickList">
</div>
</body>
</html>

jQuery hide if either div is visible

I have 2 divs that are initially hidden
<div id="whistle" style="display:none;">
<div id="lean" style="display:none;">
I also have a div that is visible
<div id="me" style="display:block">
I have jQuery code that allows only the #whistle or #lean divs to be open at once, their buttons will hide the other.
I currently have code that also hides the #me div, but I would now like the #me div to open back up when both #whistle and #lean are closed.
If you want to see the site, the link is maxdev.tk
The jQuery code is
$(document).ready(function(){
$("#calc").click(function(){
$("#whistle").hide(600);
$("#lean").toggle(900);
});
});
$(document).ready(function(){
$("#whi").click(function(){
$("#lean").hide(600);
$("#whistle").toggle(900);
});
});
This is one way to solve it. Find it also as a pen at the end of this post.
$(document).ready(function() {
function callback() {
if( $('#whistle').hasClass('hidden') && $('#lean').hasClass('hidden') ) {
$('#me').removeClass('hidden');
} else {
$('#me').addClass('hidden');
}
}
$('button[data-for=whistle]').on('click', function() {
$('#whistle').toggleClass('hidden');
$('#lean').addClass('hidden');
callback();
});
$('button[data-for=lean]').on('click', function() {
$('#lean').toggleClass('hidden');
$('#whistle').addClass('hidden');
callback();
});
})
.hidden {
opacity: 0;
height: 0;
overflow: hidden;
padding: 0;
}
div {
background-color: #ccc;
border-radius: 25px;
margin-top: 20px;
padding: 50px;
text-align: center;
transition-duration: 0.4s;
width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button data-for="whistle">Whistle</button>
<button data-for="lean">Lean</button>
<div id="whistle" class="hidden">Whistle!</div>
<div id="lean" class="hidden">Lean!</div>
<div id="me">Me!</div>
http://codepen.io/anon/pen/yNJrwe
Add this code to the end of whatever buttons' click function.
if( !$('#whistle').is(':visible') && !$('#lean').is(':visible') ) {
$('#me').css("display","block"); // or use .show();
} else {
$('#me').css("display","none"); // or use .hide();
}

Second toggel should be close when i click back to the first toggle

I have tow toggles. I want appear only one toggle at the time. When i click to second toggle then first toggle should be close.
Javascript
$('#bar').click(function () {
$('#foo').slideToggle('slow');
});
$('#bar1').click(function () {
$('#foo1').slideToggle('slow');
});
HTML
<button id="bar">bar</button>
<div id="foo"></div>
<button id="bar1">bar1</button>
<div id="foo1"></div>
CSS
#foo {
width: 100px;
height: 100px;
background-color: green;
display:none;
}
#foo1 {
width: 100px;
height: 100px;
background-color: green;
display:none;
}
jsfiddle
You can use classes instead of id's
$('.bar').click(function () {
$('.foo').hide(); // hide previous elements
$(this).next().show('slow'); // show next element in the DOM (it will be <div> with class 'foo')
});
Example
I did what you want with classes,
the accordion style,
$('#bar, #bar1').click(function () {
var id = '#'+$(this).attr('data-for');
if ($(id).hasClass('open')) {
$(id).toggleClass('open');
}
else if ($('#foo').hasClass('open') || $('#foo1').hasClass('open')) {
$('#foo').toggleClass('open');
$('#foo1').toggleClass('open');
}
else {
$(id).toggleClass('open');
}
});
#foo {
width: 100px;
height: 0;
background-color: green;
display:block;
transition: all .5s;
}
#foo1 {
width: 100px;
height: 0;
background-color: green;
display:block;
transition: all .5s;
}
#foo.open, #foo1.open {
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="bar" data-for="foo">bar</button>
<div id="foo"></div>
<button id="bar1" data-for="foo1">bar1</button>
<div id="foo1"></div>
hi i have two ways which you can achive it
in this case the first div is sliding up when second div is opening
$('#bar').click(function () {
$("div").slideUp("slow");
$('#foo').slideToggle('slow');
});
$('#bar1').click(function () {
$("div").slideUp("slow");
$('#foo1').slideToggle('slow');
});
case 1 in fiddler
in second case am hiding the first div when am opening the second div
$('#bar').click(function () {
$("div").hide();
$('#foo').slideToggle('slow');
});
$('#bar1').click(function () {
$("div").hide();
$('#foo1').slideToggle('slow');
});
case 2 in fiddler
i hope my answer helps you :)

Categories

Resources