How to delete an item from a drag and drop menu - javascript

I'm trying to add an Delete button function to a drag and drop shopping cart. I have the button in place but I can not call a function that seems to work. I'm very novice.
Im not sure if were the function should appear because the list is created from a drag and drop menu
Below is the code so far - any help would be greatly appreciated
thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Drag and Drop Shopping Cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.products1 { grid-area: products1; }
.menu1 { grid-area: menu1; }
.menu2 { grid-area: menu2; }
.menu3 { grid-area: menu3; }
.menu4 { grid-area: menu4; }
.grid-container {
display: grid;
grid-template-areas:
'products1 menu1 menu2 menu3 menu4'
;
grid-gap: 5px;
background-color: #2196F3;
padding: 5px;
}
.grid-container > div {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
padding: 20px 0;
font-size: 20px;
}
#item-container{
width: 280px;
padding: 10px;
border: 5px solid gray;
margin:20px auto;
text-align: center;
font-size: 20px;
}
ul, li{
list-style: none;
margin: 2px;
padding: 0px;
cursor: grabbing;
}
section#cart ul{
height: 600px;
overflow: auto;
background-color: #cccccc;
}
</style>
<script src="jquery-3.3.1.min.js"></script>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var items = document.querySelectorAll("section.products ul li");
var cart = document.querySelectorAll("#cart ul")[0];
function updateCart(){
var total = 0;
var term = 48;
var rate = 7;
var amount = 15090;
var cart_items = document.querySelectorAll("#cart ul li")
for (var i = 0; i < cart_items.length; i++) {
var cart_item = cart_items[i];
var quantity = cart_item.getAttribute('data-quantity');
var price = cart_item.getAttribute('data-price');
var payment = amount*((((rate/12)/100)*((1+((rate/12)/100))**term))/(((1+((rate/12)/100))**term)-1));
var sub_total = parseFloat(quantity * parseFloat(price));
cart_item.querySelectorAll("span.sub-total")[0].innerHTML = + sub_total.toFixed(2);
total += sub_total*((((rate/12)/100)*((1+((rate/12)/100))**term))/(((1+((rate/12)/100))**term)-1));
newpayment=total+payment
}
document.querySelectorAll("#cart span.total")[0].innerHTML = total.toFixed(2);
document.querySelectorAll("#cart span.newpayment")[0].innerHTML = newpayment.toFixed(2);
}
function addCartItem(item, id) {
var clone = item.cloneNode(true);
clone.setAttribute('data-id', id);
clone.setAttribute('data-quantity', 1);
clone.removeAttribute('id');
var fragment = document.createElement('span');
fragment.setAttribute('class', 'quantity');
fragment.innerHTML = '<button id="butt" onclick="one(this);">delete item</button> $';
clone.appendChild(fragment);
fragment = document.createElement('span');
fragment.setAttribute('class', 'sub-total');
clone.appendChild(fragment);
cart.appendChild(clone);
}
function updateCartItem(item){
var quantity = item.getAttribute('data-quantity');
quantity = parseInt(quantity) + 1
item.setAttribute('data-quantity', quantity);
var span = item.querySelectorAll('span.quantity');
span[0].innerHTML = ' x ' + quantity;
}
function onDrop(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var id = event.dataTransfer.getData("Text");
var item = document.getElementById(id);
var exists = document.querySelectorAll("#cart ul li[data-id='" + id + "']");
{
addCartItem(item, id);
}
updateCart();
return false;
}
function onDragOver(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
return false;
}
addEvent(cart, 'drop', onDrop);
addEvent(cart, 'dragover', onDragOver);
function onDrag(event){
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.dropEffect = "move";
var target = event.target || event.srcElement;
var success = event.dataTransfer.setData('Text', target.id);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.setAttribute("draggable", "true");
addEvent(item, 'dragstart', onDrag);
};
});
</script>
</head>
<body>
<div id="page">
<div class="grid-container">
<div class="products1">
<section id="products" class="products">
<h1></h1>
<ul>
<li id="product-1" data-price="3999.00"><div id="item-container">Product 1<br> descr<br>descr </div></li>
<li id="product-2" data-price="1895"><div id="item-container">Product 2<br> descr<br>descrip</div></li>
<li id="product-3" data-price="2.99"><span>Product 3</span></li>
<li id="product-4" data-price="3.50"><span>Product 4</span></li>
<li id="product-5" data-price="4.25"><span>Product 5</span></li>
<li id="product-6" data-price="6.75"><span>Product 6</span></li>
<li id="product-7" data-price="1.99"><span>Product 7</span></li>
</ul>
</section>
</div>
<div class="menu1">
<section id="cart" class="shopping-cart">
<h1>Preferred</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
<p> $<span class="newpayment">0.00</span></p>
</section>
</div>
<div class="menu2">
<section id="cart" class="shopping-cart">
<h1>Value</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
<div class="menu3">
<section id="cart" class="shopping-cart">
<h1>Basic</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
<div class="menu4">
<section id="cart" class="shopping-cart">
<h1>Economy</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
</div>
</div>
</body>
</html>

Related

Why is my text output from next() and prev() toggle incorrect?

When clicking the arrows to change the displayed option, the incorrect options is shown.
The user should be able click on the option menu to toggle it open/cosed and be able to click on a option to select it. Alternatively, the arrows could be used to toggle through the options instead.
This is the problematic code:
<script>
$("#arrow_left_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $("#left_menu__variant_physics").children();
divs.eq((divs.index($selected) - 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
$("#arrow_right_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $selected.parent().children();
divs.eq((divs.index($selected) + 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
</script>
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
-It seems that the first click of the arrows isn't working and that the index function is incorrect somewhere.
The problem is this line:
$("#menu_open .button_text").text($($selected).text());
$($selected) is the option that was previously selected, so you're showing the text of the previous option, not the current option. (BTW, there's no need to wrap $selected in $(), since it's already a jQuery object.)
You should use $(".menu_option_selected").text() instead of $($selected).text() to get the current option.
You should also make the initial text of the button option1, so it matches the selected option.
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
Just another version, refactoring your javascript code with some Arrow functions.
const setButtonText = () => {
$("#menu_open .button_text").text(
$(".menu_option_selected").text()
);
}
const moveSelection = direction => {
var selected = $(".menu_option_selected")
var options = $("#menu").children()
var newIndex;
if (direction == 'right') {
newIndex = (options.index(selected) + 1) % options.length
} else {
newIndex = (options.index(selected) - 1) % options.length
}
selected.removeClass("menu_option_selected")
options.eq(newIndex).addClass("menu_option_selected")
setButtonText()
}
// inizilize menu button_text
setButtonText()
$("#arrow_left").click(() => moveSelection('left'));
$("#arrow_right").click( () => moveSelection('right'));
$("#menu_open").click( () => $("#menu").toggle());
$(".menu_option").click( function() {
$(".menu_option_selected").removeClass("menu_option_selected")
$(this).addClass("menu_option_selected")
setButtonText()
});

Fruit ninja type game in javascript

I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>

Input is returning a zero

I'm trying to do a little practicing on my own, combining elements of Jon Duckett's JavaScript and JQuery book with those of Treehouse's JavaScript Basics track. Basically the program allows someone to type in text and see how much it would cost to make a sign with that text.
When I try to copy the text from the input element and place it next to custom sign, my input.value returns a zero. Any help would be greatly appreciated with figuring this out
var btnCalc = document.getElementById('myButton');
// Here's where I have the issue
var textInput = document.getElementById('textInput').value;
var customSign = document.getElementById('customSign');
var totalTiles = textInput.length;
var subtotal = totalTiles * 5;
var shipping = 7;
var grandTotal = subtotal + shipping;
btnCalc.addEventListener('click', Calculate);
function Calculate() {
// and here
document.getElementById('customSign').innerHTML = textInput;
document.getElementById('totalTiles').textContent = totalTiles;
document.getElementById('subtotal').textContent = subtotal;
document.getElementById('shipping').textContent = shipping;
document.getElementById('grandTotal').textContent = grandTotal;
}
h2 {
text-align: center;
}
span {
font-weight: bold;
}
div {
margin: 0 auto;
width: 400px;
overflow: auto;
}
ul {
list-style-type: none;
}
#right-col {
float: right;
}
#left-col {
float:left;
}
#input-form {
text-align: center;
}
<html>
<head>
<title>Duckett Chapter 2 Example</title>
<link href="styles.css" rel="stylesheet "type="text/css" >
</head>
<body>
<h2 id="greeting">Howdy Molly, please check your order: </h2>
<div>
<ul id="left-col">
<li><span>Custom Sign: </span> </li>
<li><span>Total Tiles: </span></li>
<li><span>Subtotal: </span></li>
<li><span>Shipping: </span></li>
<li><span>Grand Total: </span></li>
</ul>
<ul id="right-col">
<li id="customSign">Montague Hotel</li>
<li id="totalTiles">14</li>
<li id="subtotal">$70</li>
<li id="shipping">$7</li>
<li id="grandTotal">$77</li>
</ul>
<div id="input-form">
<input id="textInput" type="text">
<button id="myButton">Calculate</button>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
Your variables have to be inside your function, otherwise their values are already empty when you call it.
var btnCalc = document.getElementById('myButton');
btnCalc.addEventListener('click', Calculate);
function Calculate() {
var textInput = document.getElementById('textInput').value;
var customSign = document.getElementById('customSign');
var totalTiles = textInput.length;
var subtotal = totalTiles * 5;
var shipping = 7;
var grandTotal = subtotal + shipping;
document.getElementById('customSign').innerHTML = textInput;
document.getElementById('totalTiles').textContent = totalTiles;
document.getElementById('subtotal').textContent = subtotal;
document.getElementById('shipping').textContent = shipping;
document.getElementById('grandTotal').textContent = grandTotal;
}
Move calculation part to the function.
var btnCalc = document.getElementById('myButton');
// Here's where I have the issue
var textInput = document.getElementById('textInput');
var customSign = document.getElementById('customSign');
btnCalc.addEventListener('click', Calculate);
function Calculate() {
var totalTiles = textInput.value.length;
var subtotal = totalTiles * 5;
var shipping = 7;
var grandTotal = subtotal + shipping;
// and here
document.getElementById('customSign').innerHTML = textInput.value;
document.getElementById('totalTiles').textContent = totalTiles;
document.getElementById('subtotal').textContent = subtotal;
document.getElementById('shipping').textContent = shipping;
document.getElementById('grandTotal').textContent = grandTotal;
}
h2 {
text-align: center;
}
span {
font-weight: bold;
}
div {
margin: 0 auto;
width: 400px;
overflow: auto;
}
ul {
list-style-type: none;
}
#right-col {
float: right;
}
#left-col {
float:left;
}
#input-form {
text-align: center;
}
<html>
<head>
<title>Duckett Chapter 2 Example</title>
<link href="styles.css" rel="stylesheet "type="text/css" >
</head>
<body>
<h2 id="greeting">Howdy Molly, please check your order: </h2>
<div>
<ul id="left-col">
<li><span>Custom Sign: </span> </li>
<li><span>Total Tiles: </span></li>
<li><span>Subtotal: </span></li>
<li><span>Shipping: </span></li>
<li><span>Grand Total: </span></li>
</ul>
<ul id="right-col">
<li id="customSign">Montague Hotel</li>
<li id="totalTiles">14</li>
<li id="subtotal">$70</li>
<li id="shipping">$7</li>
<li id="grandTotal">$77</li>
</ul>
<div id="input-form">
<input id="textInput" type="text">
<button id="myButton">Calculate</button>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>

How to make accordion in pure javascript and html

I want this list to behave as an accordion. I have to do this in pure javascript without using jQuery or other external libraries. I am not allowed to adjust the HTML code shown below.
<ul class="accordion">
<li>Apple
<ul>
<li>abc</li>
<li>xyz</li>
<li>pqr</li>
</ul>
</li>
<li>Apple1</li>
<li>Apple2</li>
<li>Apple3</li>
<li>Apple4</li>
</ul>
I have javascript code below provided by #Ruud, which is showing accordion menu but it does not have animation effect. I want animation effect with only one item activated at a time
window.getTopUL = function() {
var uls = document.getElementsByTagName('UL');
for (var i = 0; i < uls.length; i++) {
if (uls[i].className == 'accordion') return uls[i];
}
return null;
};
window.getChild = function(li, tag) {
return li.getElementsByTagName(tag)[0];
};
window.toggleDisplay = function(s) {
s.display = s.display == 'none' ? 'block' : 'none';
};
window.setEventHandlers = function(topUL) {
if (topUL) {
var lis = document.getElementsByTagName('LI');
for (var i = 0; i < lis.length; i++) {
var ul = getChild(lis[i], 'UL');
if (ul) {
ul.style.display = 'none';
getChild(lis[i], 'A').onclick = function() {
toggleDisplay(getChild(this.parentNode, 'UL').style);
return false;
}
}
}
}
};
setEventHandlers(getTopUL());
window.getTopUL = function() {
var uls = document.getElementsByTagName('UL');
for (var i = 0; i < uls.length; i++) {
if (uls[i].className == 'accordion') return uls[i];
}
return null;
};
window.getChild = function(li, tag) {
return li.getElementsByTagName(tag)[0];
};
window.toggleDisplay = function(s) {
s.display = s.display == 'none' ? 'block' : 'none';
};
window.setEventHandlers = function(topUL) {
if (topUL) {
var lis = document.getElementsByTagName('LI');
for (var i = 0; i < lis.length; i++) {
var ul = getChild(lis[i], 'UL');
if (ul) {
ul.style.display = 'none';
getChild(lis[i], 'A').onclick = function() {
toggleDisplay(getChild(this.parentNode, 'UL').style);
return false;
}
}
}
}
};
setEventHandlers(getTopUL());
<ul class="accordion">
<li>Apple
<ul>
<li>abc
</li>
<li>xyz
</li>
<li>pqr
</li>
</ul>
</li>
<li>Apple1
</li>
<li>Apple2
</li>
<li>Apple3
</li>
<li>Apple4
</li>
</ul>
You can do it with simple html and css also
/* Clean up the lists styles */
ul.accordion {
list-style: none;
margin: 0;
padding: 0;
}
/* Hide the radio buttons */
/* These are what allow us to toggle content panes */
ul.accordion label + input[type='radio'] {
display: none;
}
/* Give each content pane some styles */
ul.accordion li {
background-color: #CCCCCC;
border-bottom: 1px solid #DDDDDD;
}
/* Make the main tab look more clickable */
ul.accordion label {
background-color: #666666;
color: #FFFFFF;
display: block;
padding: 10px;
}
ul.accordion label:hover {
cursor: pointer;
}
/* Set up the div that will show and hide */
ul.accordion div.content {
overflow: hidden;
padding: 0 10px;
display: none;
}
/* Show the content boxes when the radio buttons are checked */
ul.accordion label + input[type='radio']:checked + div.content {
display: block;
}
<ul class='accordion'>
<li>
<label for='cp-1'>Content pane 1</label>
<input type='radio' name='a' id='cp-1' checked='checked'>
<div class='content'>
<p>content to be displayed</p>
</div>
</li>
<li>
<label for='cp-2'>Content pane 2</label>
<input type='radio' name='a' id='cp-2'>
<div class='content'>
<p>content to be displayed</p>
</div>
</li>
<li>
<label for='cp-3'>Content pane 3</label>
<input type='radio' name='a' id='cp-3'>
<div class='content'>
<p>content to be displayed</p>
</div>
</li>
<li>
<label for='cp-4'>Content pane 4</label>
<input type='radio' name='a' id='cp-4'>
<div class='content'>
<p>content to be displayed</p>
</div>
</li>
<li>
<label for='cp-5'>Content pane 5</label>
<input type='radio' name='a' id='cp-5'>
<div class='content'>
<p>content to be displayed</p>
</div>
</li>
</ul>

Multiple drop events in HTML5

I'm trying to create a drag and drop feature in HTML5 where I can drag from one list to another. I have one list with draggable items and another list with items that have drop events added. The problem is, regardless of what element I drop onto, the last drop event that was added is the one that gets called.
Thanks for any help or suggestions.
I've included my code below:
<!DOCTYPE html>
<head>
<title>List Conversion Test</title>
<style type="text/css">
#list, #cart {
display: inline;
float: left;
border: 1px solid #444;
margin: 25px;
padding: 10px;
}
#list p {
background-color: #036;
color: #fff;
}
#cart p {
background-color: #363;
color: #fff;
}
.listitem {
}
.listitem_done {
text-decoration: line-through;
}
.product {
background-color: #CCC;
}
.product_over {
background-color: #363;
}
</style>
<script type="text/javascript" src="http://html5demos.com/js/h5utils.js"></script>
</head>
<body>
<article>
<div id="list">
<p>On My List</p>
<ul>
<li class="listitem" id="L001">Shopping List Item #1</li>
<li class="listitem" id="L002">Shopping List Item #2</li>
</ul>
<div id="done">
<p>In My Cart</p>
<ul></ul>
</div>
</div>
<div id="cart">
<p>Cart</p>
<ul>
<li class="product" id="P001">Product #1</li>
<li class="product" id="P002">Product #2</li>
</ul>
</div>
</article>
<script>
// make list items draggable
var list = document.querySelectorAll('li.listitem'), thisItem = null;
for (var i = 0; i < list.length; i++) {
thisItem = list[i];
thisItem.setAttribute('draggable', 'true');
addEvent(thisItem, 'dragstart', function (e) {
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData('Text', this.id);
});
}
// give products drop events
var products = document.querySelectorAll('li.product'), thisProduct = null;
for (var i = 0; i < products.length; i++) {
thisProduct = products[i];
addEvent(thisProduct, 'dragover', function (e) {
if (e.preventDefault) e.preventDefault();
this.className = 'product_over';
e.dataTransfer.dropEffect = 'copy';
return false;
});
addEvent(thisProduct, 'dragleave', function () {
this.className = 'product';
});
addEvent(thisProduct, 'drop', function (e) {
//alert(thisProduct.id);
if (e.stopPropagation) e.stopPropagation();
var thisItem = document.getElementById(e.dataTransfer.getData('Text'));
thisItem.parentNode.removeChild(thisItem);
thisProduct.className = 'product';
handleDrop(thisItem, thisProduct);
return false;
});
}
// handle the drop
function handleDrop(i, p) {
alert(i.id + ' to ' + p.id);
var done = document.querySelector('#done > ul');
done.appendChild(i);
i.className = 'listitem_done';
}
</script>
</body>
</html>
This is why it's often a bad idea to define functions (such as callback functions) within a loop. You're assigning thisProduct within the loop, but it will be reassigned for the next iteration of the loop. The way your closures are set up, each callback is bound to the same variable thisProduct, and will use the latest value.
One possible fix is to create a new closure where thisProduct is needed such as
(function(thisProduct) {
addEvent(thisProduct, 'drop', function (e) {
//alert(thisProduct.id);
if (e.stopPropagation) e.stopPropagation();
var thisItem = document.getElementById(e.dataTransfer.getData('Text'));
thisItem.parentNode.removeChild(thisItem);
thisProduct.className = 'product';
handleDrop(thisItem, thisProduct);
return false;
});
}(thisProduct));
This jsFiddle seems to work for me now. See here for more explanation.

Categories