I'm trying to create a javascript class for a droparea, I tried two different ways. Droparea class allows me to access the properties of the object but when the drop event occurs, e.preventDefault does not work. The class Droparea2 allows to avoid the default behavior of the drop event, but it does not allow me to access the properties of the object, 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>