Link to home
Start Free TrialLog in
Avatar of coolispaul
coolispaulFlag for United States of America

asked on

Javascript drag and drop

Hi,

Im trying to make a basic drag and drop example.

i have example here: https://dl.dropboxusercontent.com/u/35928349/test/index.html

Dark grey square is my drop target.
This seems to work but sometimes it doesnt - any ideas? ie you drag something over the grey box and it doesnt always recognise that.

Also i want to animate the objects so that if someone drops an object outside the grey box it transitions it back to its original position using css3 animations.
Ive attempted this but it doesnt work as intended

Help appreciated!
SOLUTION
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I am with AlexCode on this - JQueryUI has solved a lot of the problems you want to solve.

I have done a lot of similar work to what you are doing using JQueryUI - it was quite easy in the end.
Avatar of coolispaul

ASKER

yeah i just wanted to try it natively rather than use jquery as i am learning javascript.

I see in jquery when you drag something it actually moves it rather than create a ghost copy of itself. How can i replicate that in javascript alone?

Thanks
To move items around they have to have a position:absolute set.
When this is set you need to translate the element relative position to its absolute position.
For this you need to use the element's properties:
var elem = document.getElementById("myDiv");
var posX = elem.offsetLeft;
var posY = elem.offsetTop;
var width = elem.offsetWidth;
var height = elem.offsetHeight;

Open in new window


Have a look here to get the correct element dimension:
https://developer.mozilla.org/en-US/docs/Determining_the_dimensions_of_elements

Then you just have to play with it position relative to the mouse pointer and handle the mouse down and mouse up events.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial