0

I'm doing a drag and drop thing. When the user grabs the element I need to add an event listener for dragenter to every element. In that listener function I need it to get and save the clientX when the mouse moves over that element. The issue I'm having is it gets the mouse position of the first element and keeps the same one for every other element. How can I fix this?

Code:

if(editor_children[i].nodeType != 3)
    {
        editor_children[i].addEventListener("dragenter", function(event){
            if(event.target.id !== e.target.id) event.target.className= event.target.className + " highlight";
            position= event.clientX;
            last_over= event.target.id;
            console.log("Mouse: " + e.clientX + " Position: " + position + " Last Element: " + last_over);
        })
        
        editor_children[i].addEventListener("dragleave", function(event){
            event.target.className= event.target.className.replace(' highlight', '');
        });
    }

Please no JS libraries.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Zaper127
  • 155
  • 1
  • 2
  • 11
  • Just at first glance, might it be because you're using the same variable (the position variable) to store every position of every element? You're also making this pretty hard on yourself. Just do function(e){e=e||event; and use e for everything. – tomysshadow Jul 05 '15 at 21:00
  • The position variable is a global (yes, I know, bad coding. Going to be fixed later) needed for the drop function.. I found the issues though, thanks. – Zaper127 Jul 05 '15 at 21:32

1 Answers1

0

This is why I'm not a huge fan of JavaScript. anyways, the issue was cause by me creating a function inside a loop, so it was using the same value every time, instead of a variable value. I just learned this by running it threw JShint. Also I had to clear the functions between drag and drop calls to avoid issues with stored data. It's hard to explain but I got it.

Zaper127
  • 155
  • 1
  • 2
  • 11