i am trying to create a javascript class for a droparea, i tried two different ways. The Droparea class allows me to access the object's properties but when the drop event occurs, e.preventDefault does not work. The Droparea2 class allows me to avoid the default behavior of the drop event, but it does not allow me to access the object's properties. Any solution? I prefer not to use any plugin.
class Droparea {
// Contructor
constructor(div, property1){
this.div = div;
this.property1 = property1;
}
// Metodos
registerEvents(){
this.in();
this.out();
this.drop();
return;
}
in(){
var div = this.div;
var property1 = this.property1;
div.addEventListener('dragover',function(){
div.style.background = "yellow";
div.innerHTML = property1 + '1';
},false);
}
out(){
var div = this.div;
var property1 = this.property1;
div.addEventListener('dragleave',function(e){
e.stopPropagation();
e.preventDefault();
div.style.background = "blue";
div.innerHTML = property1 + '2';
},false);
}
drop(){
var div = this.div;
var property1 = this.property1;
div.addEventListener('drop',function(e){
e.stopPropagation();
e.preventDefault();
div.style.background = "red";
div.innerHTML = property1 + '3';
},false);
}
}
class Droparea2 {
// Contructor
constructor(div, property1){
this.div = div;
this.property1 = property1;
}
// Metodos
registerEvents(){
this.div.addEventListener('dragover',this.in,false);
this.div.addEventListener('dragleave',this.out,false);
this.div.addEventListener('drop',this.drop,false);
}
in(e){
e.stopPropagation();
e.preventDefault();
e.target.style.background = 'yellow';
}
out(e){
e.stopPropagation();
e.preventDefault();
e.target.style.background = 'blue';
e.target.innerHTML = this.property1;
}
drop(e){
e.stopPropagation();
e.preventDefault();
e.target.style.background = 'red';
}
}
var div = document.querySelector('.droparea');
var drop = new Droparea(div,'Something');
var div2 = document.querySelector('.droparea2');
var drop2 = new Droparea2(div2,'Something');
drop.registerEvents();
drop2.registerEvents();
.droparea {
background: gray;
height: 200px;
}
.droparea2 {
background: darkgray;
height: 200px;
}
<div class="droparea">Arrastra tu elemento aqui. 1</div>
<div class="droparea2">Arrastra tu elemento aqui. 2</div>
If you register the listeners, the problem is that you forgot to prevent the default action on the event
dragover
:Remember that you must prevent events in events
dragover
,dragleave
anddrop
if you want to customize behaviors. Also, if you want to use adataTransfer
you can simulate one with an instance object, since the original objectdataTransfer
is only available indragstart
anddrop
. I leave you an example of this.Example DnD and File API