i am working on my game but i have some problems...
1. if the image is in the class .room it has a another src but if you drop it in the class .items it should change to a icon. And if you drag it again to .room it will turn back.
2. There are many different image so i want to have a switch. if the draged objekt is dragging to .items the image should change. so the id of the image should go to the switch and check if the id and case is the same. the scr should be from the icon.
3. if it is possible i want to safe the id of the image in local.storage so i can use the objekt in the next page
<html>
<head>
<style>
.room {
width: 500px;
height: 150px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
.items {
width: 500px;
height: 150px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
<script>
function allowDrop(ev) {
if (ev.target.className === "items") {
ev.target.style.border = "3px dashed black";
}
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("img", ev.target.id);
}
function dragleave(ev) {
if (ev.target.className === "items") {
ev.target.style.border = "0px dashed transparent";
}
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("img");
ev.target.style.border = "0px dashed transparent";
if (ev.target=="[object HTMLImageElement]"){
ev.target = ev.target.parentNode;
}
else {
ev.target.appendChild(document.getElementById(data));
}
if (ev.target.id === ev.dataTransfer.getData("ori")) {
return;
}
var image = document.createElement("img");
image.id =
image.draggable = true;
image.addEventListener('dragstart', drag);
if (ev.target.className === 'items') {
icon();
} else if (ev.target.className === 'room') {
room();
}
var originEle = document.getElementById(ev.dataTransfer.getData("ori"));
originEle.outerHTML = '';
delete originEle;
ev.target.appendChild(image);
}
function icon(){
switch(image.id) {
case "teddy": image.src="pic/Icons/teddy.png";break;
case "book": image.src="pic/Icons/Buch.png";break;
}
}
function room(){
switch(image.id) {
case "teddy": image.src= "pic/Home/HomeRoom_booksL.png";break;
case "booksR": image.src= "pic/Home/HomeRoom_buch.png";break;}
}
function reset(){
var container = document.getElementById("field");
container.innerHTML= html;
}
var html;
window.onload = function(){
html = document.getElementById('field').innerHTML;
};
</script>
</head>
<body>
<h2>Drag and Drop</h2>
<div>
<div class="room" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<h2>items</h2>
<div class="items" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="book" src="pic/Icons/Buch.png" draggable="true" ondragstart="drag(event)" id="drag1">
<img id="teddy" alt="booksL"src="pic/Home/HomeRoom_teddy.png" id="drag2" draggable="true" ondragstart="drag(event)" >
</div>
</div>
</body>
</html>
About the 3rd question - saving to localStorage:
add the code below to your drop function.
localStorage.setItem("name", data);
Related
I have some code which tries to display temporary images from tempimages[] to img src with id=slide of box002, according to the random number selected from arrayVariable to ptag[i].
I want to display tempimages[0] first on img src of class box002, after dropping that image it gets deleted by the function Drop(ev), after that tempimages[i] should display img src of box002 for dropping likewise.
How to display images from an image array tempimages to class box img src?
I have used the function displayAllImages() to allocate images to img src id=slide, but it failed to display images.
box002 can be dragged and dropped to any box.
I want to display each image one by one from tempimages[] to img src of the box after each drop. How to change the code to achieve this property?
var tempimages = [];
function rvalue() {
var array = [];
var arrayVariable = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
var ArrayOfImages = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'];
arrayLength = arrayVariable.length;
ptags = document.getElementsByName("values");
for (i = 0; i < ptags.length; i++) {
ptags[i].innerHTML = arrayVariable[Math.floor(Math.random() * arrayLength)];
array.push(ptags[i].textContent);
tempimages.push(`${ptags[i].textContent}.jpg`); // want to display array to box002 to imgtag
}
}
function displayAllImages() {
var
i = 0,
len = tempimages.length;
for (; i < tempimages.length; i++) {
var img = new Image();
img.src = tempimages[i];
img.style.width = '100px';
img.style.height = '100px';
document.getElementById('slide').appendChild(img);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var el = document.getElementById(data);
el.parentNode.removeChild; // deleting drag item
ev.target.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none
var pParagraph = ev.target.firstElementChild;
ev.target.removeChild(pParagraph);
alert(el);
}
#container {
margin-top:-2%;
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.box {
background-color: coral;
width: 60px;
height:60px;
margin-top:10px;
display:inline-block;
border-radius:5px;
border:2px solid #333;
border-color: #e6e600;
border-radius: 10%;
background-color: #ffcc00;
}
.box002 {
float: left;
width: 50px;
height: 50px;
float: left;
margin-left:30%;
padding-top:2%;
background-color:#ffff00 2px;
border:2px solid #000066;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
#container {
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="rvalue()">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>
</div>
</body>
I'm not a 100% sure what it is you're trying achieve but here is something which might get you to the where you want to get. It picks three items at random and updates the image in the slide element after each time the slide is dropped on one of the boxes.
I've made a couple of changes, see the comments in the code as to why I've made the changes. When I saw this code first I didn't understand the need for two separate arrays so I've merged them into a single array.
var tempimages = [];
function rvalue() {
const
items = [
{ label: '1', url: 'https://via.placeholder.com/75x75?text=1' },
{ label: '2', url: 'https://via.placeholder.com/75x75?text=2' },
{ label: '3', url: 'https://via.placeholder.com/75x75?text=3' },
{ label: '4', url: 'https://via.placeholder.com/75x75?text=4' },
{ label: '5', url: 'https://via.placeholder.com/75x75?text=5' },
{ label: '6', url: 'https://via.placeholder.com/75x75?text=6' },
{ label: '7', url: 'https://via.placeholder.com/75x75?text=7' },
{ label: '8', url: 'https://via.placeholder.com/75x75?text=8' },
{ label: '9', url: 'https://via.placeholder.com/75x75?text=9' },
{ label: '10', url: 'https://via.placeholder.com/75x75?text=10' }
],
ptags = Array.from(document.querySelectorAll('[name="values"]'));
ptags.forEach(ptag => {
const
// Generate a random index.
randomIndex = Math.floor(Math.random() * items.length),
// Get the at item from the random index (it is possible the same item
// gets picked multiple times as there is no check for duplicates).
item = items[randomIndex];
// Update the label
ptag.textContent = item.label;
// Push the item into the array.
tempimages.push(item);
});
}
function displayAllImages() {
// Check if there are still images in the array, if not exit.
if (tempimages.length === 0) {
return;
}
const
// Remove the item at index 0 from the array.
item = tempimages.shift(),
// Get the image element.
image = document.getElementById('slide');
// Update src attribute so it points to the new URL.
image.src = item.url;
};
$(function() {
// On start, do rvalue first. This is taken from the onload in the body
// as that fired later than this method which meant displayAllImages was
// called before rvalue.
rvalue();
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var el = document.getElementById(data);
el.parentNode.removeChild; // deleting drag item
// ev.currentTarget is a div with class box whereas target can
// be either the div or the p element. Using currentTarget ensures
// you know which element you're working with.
ev.currentTarget.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none
var pParagraph = ev.currentTarget.firstElementChild;
ev.currentTarget.removeChild(pParagraph);
// Show the next image in the slider..
displayAllImages();
}
#container {
margin-top:-2%;
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.box {
background-color: coral;
width: 60px;
height:60px;
margin-top:10px;
display:inline-block;
border-radius:5px;
border:2px solid #333;
border-color: #e6e600;
border-radius: 10%;
background-color: #ffcc00;
}
.box002 {
float: left;
width: 50px;
height: 50px;
float: left;
margin-left:30%;
padding-top:2%;
background-color:#ffff00 2px;
border:2px solid #000066;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
#container {
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>
</div>
</body>
I have simple table with two cells. I change w3 school code(for drag and drop) to one image, when drag over second, take second image place and second image disappears. But problem come when there is no image in cell, then cell is gone. How to check is there image in cell?
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var el = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
el.appendChild(document.getElementById(data).cloneNode(true));
var x = el.classList.contains('dropzone');
if (!x) {
ev.target.remove();
}
}
th, td{
border: solid black;
width: 100px;
height: 100px;
padding: 0px;
}
table{
width: 300px;
}
img{
width: 100px;
}
<table>
<tr>
<td ondrop="drop(event)" ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="a8" src="http://images5.fanpop.com/image/photos/27700000/desert-windows-7-vista-and-xp-picks-27752343-500-375.jpg"></td>
<td ondrop="drop(event)" ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="b8" src="http://images5.fanpop.com/image/photos/27700000/jellyfish-windows-7-vista-and-xp-picks-27753183-500-375.jpg"></td>
</tr>
</table>
you can loop throught td elements and add ondrop event in you javascript code, So you can know which element has fired the event.
Then check if this element has a child inside.
If not => don't perform action (no image elements inside), else => perform action (there is an image elements inside).
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
var td=document.getElementsByTagName("td");
for(var i=0; i < td.length;i++){ //bind ondrop event to all td, so it will be easier to get the element which fired the event
td[i].ondrop=function(ev){
ev.preventDefault();
if (this.hasChildNodes()) { //check if got children nodes (if got img inside)
var data = ev.dataTransfer.getData("text");
var el = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
el.appendChild(document.getElementById(data).cloneNode(true));
var x = el.classList.contains('dropzone');
if (!x) {
ev.target.remove();
}
}
}
}
th, td{
border: solid black;
width: 100px;
height: 100px;
padding: 0px;
}
table{
width: 300px;
}
img{
width: 100px;
}
<table>
<tr>
<td ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="a8" src="http://images5.fanpop.com/image/photos/27700000/desert-windows-7-vista-and-xp-picks-27752343-500-375.jpg"></td>
<td ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="b8" src="http://images5.fanpop.com/image/photos/27700000/jellyfish-windows-7-vista-and-xp-picks-27753183-500-375.jpg"></td>
</tr>
</table>
For more details how to check if element has any children, check answers here
How can make a draggable element to remain displayed on its source box after being dragged?
Below the script to illustrate it:
function dragStart(ev) {
ev.dataTransfer.setData('text1', ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text1');
ev.target.appendChild(document.getElementById(data));
}
function allowDrop(ev) {
ev.preventDefault();
}
.boxarticle {
width: 200px;
height: 150px;
border: 1px solid blue;
margin: 0 0 10px 20
}
div#panier {
width: 150px;
height: 150px;
background-color: ;
border: 1px solid blue;
}
<!-- I want that image to remain here after I dragged it -->
<div class='boxarticle'>
<img src="https://cdn-images-1.medium.com/max/1200/1*QQvzwKk7rdC1JkY0XiPVUQ.png" draggable="true" id='image' data-price='9200' ondragstart="dragStart(event)" width=80 height=80>
</div>
<!-- where draggable element go in -->
<div id="panier" ondrop='drop(event)' ondragover="allowDrop(event)"> Drag and drop image here..but leave it in the source place </div>
You need to clone it and give it a new id, otherwise it will assume "drag".
HTML5 drag and copy?
function dragStart(ev)
{
ev.dataTransfer.setData('text1',ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("text1");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "randomId";
ev.target.appendChild(nodeCopy);
}
function allowDrop(ev)
{
ev.preventDefault();
}
.boxarticle {
width:200px;height: 150px; border:1px solid blue;margin: 0 0 10px 20
}
div#panier {
width:150px;height: 150px;background-color: ; border: 1px solid blue;
}
<!-- I want that image to remain here after I dragged it -->
<div class='boxarticle'>
<img src="https://cdn-images-1.medium.com/max/1200/1*QQvzwKk7rdC1JkY0XiPVUQ.png" draggable="true" id='image' data-price='9200' ondragstart="dragStart(event)" width=80 height=80>
</div>
<!-- where draggable element go in -->
<div id="panier" ondrop='drop(event)' ondragover="allowDrop(event)"> Drag and drop image here..but leave it in the source place </div>
im trying to get a set of four different colored div's to flash for a second in a random sequence that keeps repeating adding one more flash each time, by adding a class that sets their opacity to 0, but only the last div in the sequence appears to be flashing, here is the javascript code:
$(function() {
x="";
for(i=0;i<3;i++){
x+=String(Math.floor(Math.random()*4)+1);
$("#test").append(x);
j=0;
flashinglight();
$("#red").removeClass("redflash");
$("#blue").removeClass("blueflash");
$("#yellow").removeClass("yellowflash");
$("#green").removeClass("greenflash");
};
})
function flashinglight(){
if(j<x.length){
setTimeout(function(){
$("#red").removeClass("redflash");
$("#yellow").removeClass("yellowflash");
$("#green").removeClass("greenflash");
$("#blue").removeClass("blueflash");
if(x[j]=="1"){
$("#red").addClass("redflash");
}
else if(x[j]=="2"){
$("#yellow").addClass("yellowflash");
}
else if(x[j]=="3"){
$("#green").addClass("greenflash");
}
else if(x[j]=="4"){
$("#blue").addClass("blueflash");
}
j+=1;
flashinglight();
},1000);
}
else{
return;
}
}
You'll be glad to know it can ba a lot simpler than that. :-) See comments inline:
// Your existing ready callback
$(function() {
// Array of color names
var colors = ["red", "blue", "yellow", "green"];
// Start
flashlight();
function flashlight() {
// Get a random color
var c = colors[Math.floor(Math.random() * colors.length)];
// Get the matching element
var elm = $("#" + c);
// And class
var cls = c + "flash";
// Add the class
elm.addClass(cls);
// A second later...
setTimeout(function() {
// Remove it
elm.removeClass(cls);
// And run again
flashlight();
}, 1000);
}
});
.container div {
display: inline-block;
width: 40px;
height: 40px;
}
#red {
border: 2px solid red;
}
#blue {
border: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#green {
border: 2px solid green;
}
.redflash {
background-color: red;
}
.blueflash {
background-color: blue;
}
.yellowflash {
background-color: yellow;
}
.greenflash {
background-color: green;
}
<div class="container">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
That "flashes" for a full second before moving on to the next. If you need a shorter flash and a delay between them, it's just a matter of setting up a second timer.
Watching that for a moment, it bothered me when the same color was picked twice. So if you want a version that excludes the current color when picking the next:
// Your existing ready callback
$(function() {
// Array of color names
var colors = ["red", "blue", "yellow", "green"];
// The current color
var color = null;
// Start
flashlight();
function flashlight() {
// Pick a random color, excluding the one we're currently using
var available = colors.filter(function(c) {
return c !== color;
});
color = available[Math.floor(Math.random() * available.length)];
// Get the matching element
var elm = $("#" + color);
// And class
var cls = color + "flash";
// Add the class
elm.addClass(cls);
// A second later...
setTimeout(function() {
// Remove it
elm.removeClass(cls);
// And run again
flashlight();
}, 1000);
}
});
.container div {
display: inline-block;
width: 40px;
height: 40px;
}
#red {
border: 2px solid red;
}
#blue {
border: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#green {
border: 2px solid green;
}
.redflash {
background-color: red;
}
.blueflash {
background-color: blue;
}
.yellowflash {
background-color: yellow;
}
.greenflash {
background-color: green;
}
<div class="container">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Hoping someone can help me.
Checked other, similar questions on this forum but still can't solve this problem.
Trying to create a simple shopping cart using HTML5 (Drag and Drop) and JavaScript. I've copied most of the code below from an online tutorial (code was open source and free to use). I want to extend the code so that, as items are dragged into cart area, the total cost of all items in the cart is displayed. This total would be updated as more items are added.
Also, I'm trying to update the code so that a user can purchase more than one of any item and am trying to get the display to also show quantity of each item in cart.
I've added an updateCart() function but I'm confused as to how to get it working properly (obviously it's not functioning as intended). Since the drag and drop from original code is working the problem must be in my updateCart function.
I've added ' data-price' and 'data-quantity' attributes to the li tags of shop items. I've tried to get total price to display but haven't looked at item quantity yet.
Any advice would be appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Drag and drop in HTML 5, demonstration with a shop</title>
<style>
body {
padding:32px;
}
.shop {
border-radius:6px;
list-style-type:none;
padding:0;
margin:0;
}
.shop li{
display:inline;
}
.cart {
border: 4px solid #0066FF;
border-radius:6px;
min-height:128px;
display:block;
}
.product {
border:3px solid white;
}
.product:hover {
border:3px solid red;
cursor:move;
}
.itemchoosen {
this.style.opacity = 0.5;
this.style.border = "2px solid red";
}
.itemblurred {
this.style.border = none;
}
#cartArea {
position: relative;
height: 200px;
width: 100%;
float: left;
border: 1px dotted #999;
}
</style>
</head>
<body >
<fieldset><legend>The shop</legend>
<ul id="shop" class="shop">
<li data-price="30.00" data-quantity="1"><img class="product" id="chair" src="images/chair.jpg" width="96" height="96"></li>
<li data-price="250.00" data-quantity="1"><img class="product" id="monitor" src="images/screen.jpg" width="96" height="96"></li>
<li data-price="80.00" data-quantity="1"><img class="product" id="bag" src="images/bag.jpg" width="96" height="96"></li>
<li data-price="350.00" data-quantity="1"><img class="product" id="transat" src="images/transat.jpg" width="96" height="96"></li>
</ul>
</fieldset>
<fieldset id="mycart" class="cart"><legend>My cart</legend>
<div id="cartArea"></div>
</fieldset>
<fieldset id="mycart" class="cart"><legend>Total</legend>
<p id="the_sub_total"></p>
<p id="the_total"></p>
</fieldset>
<script>
var cartArea = document.querySelector('#cartArea');
var prods = document.querySelectorAll('.product');
for(var i = 0; i < prods.length; i++)
{
prods[i].setAttribute('draggable', 'true'); // optional with images
prods[i].addEventListener('dragstart', function(evnt) {
this.className = 'itemchoosen';
evnt.dataTransfer.effectAllowed = 'copy';
evnt.dataTransfer.setData('text', this.id);
return false;
}, false);
}
cartArea.addEventListener('dragover', function(evnt) {
if (evnt.preventDefault) evnt.preventDefault();
evnt.dataTransfer.dropEffect = 'copy';
return false;
}, false);
cartArea.addEventListener('dragenter', function(evnt) {
return false;
}, false);
cartArea.addEventListener('dragleave', function(evnt) {
return false;
}, false);
cartArea.addEventListener('drop', function(evnt) {
if (evnt.stopPropagation) evnt.stopPropagation();
var id = evnt.dataTransfer.getData('text');
var theitem = document.getElementById(id);
//theitem.parentNode.removeChild(el);
theitem.className='itemblurred';
var y = document.createElement('img');
y.src = theitem.src;
cartArea.appendChild(y);
evnt.preventDefault(); // for Firefox
updateCart();
return false;
}, false);
function updateCart(){
var total = 0.0;
var cart_items = document.querySelectorAll("#shop 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 sub_total = parseFloat(quantity * parseFloat(price));
//document.querySelectorAll("#the_sub_total")[0].innerHTML = " = " + sub_total.toFixed(2);
total += sub_total;
}
document.querySelectorAll("#the_total")[0].innerHTML = total.toFixed(2);
}
</script>
</body>
</html>
try using this code :
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Drag and drop in HTML 5, demonstration with a shop</title>
<style>
body {
padding:32px;
}
.shop {
border-radius:6px;
list-style-type:none;
padding:0;
margin:0;
}
.shop li{
display:inline;
}
.cart {
border: 4px solid #0066FF;
border-radius:6px;
min-height:128px;
display:block;
}
.product {
border:3px solid white;
}
.product:hover {
border:3px solid red;
cursor:move;
}
.itemchoosen {
this.style.opacity = 0.5;
this.style.border = "2px solid red";
}
.itemblurred {
this.style.border = none;
}
#cartArea {
position: relative;
height: 200px;
width: 100%;
float: left;
border: 1px dotted #999;
}
</style>
</head>
<body >
<fieldset><legend>The shop</legend>
<ul id="shop" class="shop">
<li data-price="30.00" data-quantity="1"><img class="product" id="chair" src="images/chair.jpg" width="96" height="96"></li>
<li data-price="250.00" data-quantity="1"><img class="product" id="monitor" src="images/screen.jpg" width="96" height="96"></li>
<li data-price="80.00" data-quantity="1"><img class="product" id="bag" src="images/bag.jpg" width="96" height="96"></li>
<li data-price="350.00" data-quantity="1"><img class="product" id="transat" src="images/transat.jpg" width="96" height="96"></li>
</ul>
</fieldset>
<fieldset id="mycart" class="cart"><legend>My cart</legend>
<div id="cartArea"></div>
</fieldset>
<fieldset id="mycart" class="cart"><legend>Total</legend>
<p id="the_sub_total"></p>
<p id="the_total"></p>
</fieldset>
<script>
var total = 0.0;
var cartArea = document.querySelector('#cartArea');
var prods = document.querySelectorAll('.product');
for(var i = 0; i < prods.length; i++)
{
prods[i].setAttribute('draggable', 'true'); // optional with images
prods[i].addEventListener('dragstart', function(evnt) {
this.className = 'itemchoosen';
evnt.dataTransfer.effectAllowed = 'copy';
evnt.dataTransfer.setData('text', this.id);
return false;
}, false);
}
cartArea.addEventListener('dragover', function(evnt) {
if (evnt.preventDefault) evnt.preventDefault();
evnt.dataTransfer.dropEffect = 'copy';
return false;
}, false);
cartArea.addEventListener('dragenter', function(evnt) {
return false;
}, false);
cartArea.addEventListener('dragleave', function(evnt) {
return false;
}, false);
cartArea.addEventListener('drop', function(evnt) {
if (evnt.stopPropagation) evnt.stopPropagation();
var id = evnt.dataTransfer.getData('text');
var theitem = document.getElementById(id);
console.log(theitem.parentNode.attributes);
var quantity=theitem.parentNode.attributes['data-quantity'].value;
var price = theitem.parentNode.attributes['data-price'].value;
console.log(price);
theitem.className='itemblurred';
var y = document.createElement('img');
y.src = theitem.src;
cartArea.appendChild(y);
evnt.preventDefault(); // for Firefox
updateCart(quantity,price);
return false;
}, false);
function updateCart(quantity,price){
var sub_total = parseFloat(quantity * parseFloat(price));
total = total+sub_total;
document.getElementById('total').value= total;
document.querySelectorAll("#the_total")[0].innerHTML = total.toFixed(2);
}
</script>
</body>
</html>
Updated Code:
You are running a loop in updateCart() to first get the price of all the items and then check what all items are there in the cart, instead you can send the price as the parameter in the updateCart() function, as you are already getting the element which is recently dropped in the cartArea.addEventListener('drop', function(evnt).
You can add a scroll to the cartArea if you want.
But I am not getting why you have used sub_total in this, if you want to show the item price below the item image, then there is no need.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Drag and drop in HTML 5, demonstration with a shop</title>
<style>
body {
padding:32px;
}
.shop {
border-radius:6px;
list-style-type:none;
padding:0;
margin:0;
}
.shop li{
display: inline-table;
}
.cart {
border: 4px solid #0066FF;
border-radius:6px;
min-height:128px;
display:block;
padding: 20px 10px;
}
.product {
border:3px solid white;
}
.product:hover {
border:3px solid red;
cursor:move;
}
.itemchoosen {
this.style.opacity = 0.5;
this.style.border = "2px solid red";
}
.itemblurred {
this.style.border = none;
}
#cartArea {
position: relative;
min-height: 200px;
width: 100%;
float: left;
}
#cartArea img {
float: left;
width: 20%;
margin: 2%;
}
.itemPrice {
width: 100%;
float: left;
}
</style>
</head>
<body >
<fieldset><legend>The shop</legend>
<ul id="shop" class="shop">
<li><img class="product" id="chair" src="images/chair.jpg" width="96" height="96" data-price="30.00" data-quantity="1"></li>
<li><img class="product" id="monitor" src="images/screen.jpg" width="96" height="96" data-price="250.00" data-quantity="1"></li>
<li><img class="product" id="bag" src="images/bag.jpg" width="96" height="96" data-price="80.00" data-quantity="1"></li>
<li><img class="product" id="transat" src="images/transat.jpg" width="96" height="96" data-price="350.00" data-quantity="1"></li>
</ul>
</fieldset>
<fieldset id="mycart" class="cart">
<legend>My cart</legend>
<div id="cartArea"></div>
</fieldset>
<fieldset id="mycart" class="cart">
<legend>Total</legend>
<p id="the_sub_total"></p>
<p id="the_total">0</p>
</fieldset>
<script>
var cartArea = document.querySelector('#cartArea');
var prods = document.querySelectorAll('.product');
var itemPriceElement;
for(var i = 0; i < prods.length; i++) {
itemPriceElement = document.createElement("span");
itemPriceElement.className = "itemPrice";
itemPriceElement.innerHTML = prods[i].getAttribute("data-price");
prods[i].parentNode.insertBefore(itemPriceElement, prods[i].nextSibling);
prods[i].setAttribute('draggable', 'true'); // optional with images
prods[i].addEventListener('dragstart', function(evnt) {
//this.className = 'itemchoosen';
this.classList.add('itemchoosen');
evnt.dataTransfer.effectAllowed = 'copy';
evnt.dataTransfer.setData('text', this.id);
return false;
}, false);
}
cartArea.addEventListener('dragover', function(evnt) {
if (evnt.preventDefault) evnt.preventDefault();
evnt.dataTransfer.dropEffect = 'copy';
return false;
}, false);
cartArea.addEventListener('dragenter', function(evnt) {
return false;
}, false);
cartArea.addEventListener('dragleave', function(evnt) {
return false;
}, false);
cartArea.addEventListener('drop', function(evnt) {
if (evnt.stopPropagation) evnt.stopPropagation();
var id = evnt.dataTransfer.getData('text');
var theitem = document.getElementById(id);
//theitem.parentNode.removeChild(el);
//theitem.className='itemblurred';
theitem.classList.add('itemblurred');
var y = document.createElement('img');
y.src = theitem.src;
cartArea.appendChild(y);
evnt.preventDefault(); // for Firefox
updateCart(theitem.getAttribute("data-price"));
return false;
}, false);
function updateCart(price){
var the_total = document.getElementById("the_total").innerHTML;
the_total = parseInt(the_total);
the_total = the_total + parseInt(price);
document.getElementById("the_total").innerHTML = the_total;
}
</script>
</body>
</html>