Reputation: 63
I have some code that is essentially a series of divs where you can drag and drop images into some of the divs, but not some of the others. I'm controlling the dragging and dropping of images with these few scripts:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
alert (ev.target);
ev.preventDefault();
if(ev.target=="[object HTMLDivElement]"){
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
}
As a result, I want to insert an image into the divs where I don't want to drop so that it registers the target where you are trying to drop the image as something other than [object HTMLDivElement], preferably [object HTMLImageElement]. Obviously background-image doesn't work, and putting the content tag in the div id in my css doesn't work either. Is there any way to do this in the CSS, or should I do it when I'm creating the div in the HTML?
EDIT: Here's the rest of my code. They style is in the head, of course.
<head>
<style>
#droppablediv{
float: left;
width: 100px;
height: 35px;
border: 1px solid black;
}
#nondroppablediv{
float:left;
width: 100px;
height: 35px;
border: 1px solid black;
background-image: url(urlhere);
}
</style>
/*
Javascript functions
*/
</head>
<body>
<div id="droppablediv" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="nondroppablediv" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img src="mydraggableimage.jpg" draggable="true" ondragstart="drag(event)" id="drag2" width="88" height="31">
</body>
And here's a jsfiddle with a working version of the code. Notice you can drag and drop an image into one box, but you can't put both in the same box.
Upvotes: 0
Views: 1277
Reputation: 28
renderImage() {
const file = ;
const reader = new FileReader();
reader.onload = function(e) {
const imageRender = `<img src=${e.target.result}>`;
document.getElementById('appendHere').innerHTML = imageRender;
};
reader.readAsDataURL(file);
}
Upvotes: -1
Reputation:
Simply use the innerHTML
tag. For example, when the user drags, get the starting cell (dragged from) and move it to the target cell (dragged to).
Then, get the HTML of the starting cell. However, the image must be in the div as HTML with a src attribute
function drag(startDivId,endDivId){
try{
var img = document.getELementById(startDivId).innerHTML
document.getElementById(endDivId).innerHTML=img
return true
} catch(e) {
return e
}
}
Upvotes: 1