Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  72] [ 3]  / answers: 1 / hits: 8191  / 10 Years ago, thu, july 31, 2014, 12:00:00

Here i am drag an element and droping in another place it works well if i don't use event listeners but if i use it in this format it is not performing place operation.



this link contains my code with Event Listeners
Visit http://jsfiddle.net/vishwateja2000/wHprQ/2/



this link contains my code without Event Listeners
Visit http://jsfiddle.net/vishwateja2000/W2Pgq/1/



document.getElementById(div2).addEventListener(mousedown, down);

function down(){
t=1;
document.getElementById(div1).addEventListener(mouseup, place);

document.getElementById(div1).addEventListener(mousemove,function() {
myFunction(event);
});
}

function place(){
document.getElementById(div1).removeEventListener(mousemove,function() {
myFunction(event);
});
}
function placeobj(x,y,x1,y1,l,r){
var cpx = parseInt(x);
var cpy = parseInt(y);
var amtx=parseInt(x1);
var amty=parseInt(y1);
var of=10;
document.getElementById(div2).style.left=cpx-amtx+l+px;
document.getElementById(div2).style.top=cpy-amty+r+px;
}
function myFunction(e) {
if(t==1){
x1 = e.clientX;
y1 = e.clientY;
var el=document.getElementById('div2');
l=el.offsetLeft;
r=el.offsetTop;
t=10;
}
x = e.clientX;
y = e.clientY;
placeobj(x,y,x1,y1,l,r);
}

More From » html

 Answers
3

The problem is that you used different functions when adding and removing the mousemove event.
Although they have the same functionality they are different functions in memory and so are treated differently.



Take a look at the fixed version:
http://jsfiddle.net/PN3TA/



The removeEventListener() has to have the same event name + function as used in the addEventListener() to remove the right event. The function can't be an anonymous function as that creates a new function (although it might look the same). You need to use a reference (like a pointer) which can be a named function or a variable.



NOTE: Also when passing a function to these methods you don't have to wrapped in an anonymous function if the original function expects to get the same arguments as the anonymous function. I mean, this:



 document.getElementById(div1).addEventListener(mousemove,function() {
myFunction(event);
});


Could be written like this, because myFunction() expects an event argument which will be supplied anyway, saving you a function wrapper:



document.getElementById(div1).addEventListener(mousemove,  myFunction);

[#43465] Wednesday, July 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;