I found the following article by Mark Kahn: How to Drag and Drop with Javascript while working on a solution for dragging and dropping boxes on web page. Mark’s example works really well except for one small problem: in Firefox, Safari, and Chrome, the boxes disappear as you drag them on top of each other…only to reappear after you’ve released the mouse button. IE works properly. While not a big issue, it’s a little annoying.
I did a little digging and found the solution. In the mouseMove function (shown in the article), there are two lines of code that find the current position of the box that’s being moved:
dragObject.style.top = mousePos.y – mouseOffset.y;
dragObject.style.left = mousePos.x – mouseOffset.x;
In order to work properly in Chrome, Firefox, and Safari, the calculations need to have to include a “+’px’” to identify the coordinates as pixels:
dragObject.style.top = mousePos.y – mouseOffset.y+’px’;
dragObject.style.left = mousePos.x – mouseOffset.x+’px’;
This should work in all Javascript enabled browsers and is technically the right way to perform calculations involving pixels.
Like this:
Be the first to like this post.
Recent Comments