coolispaul
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!
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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:
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.
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;
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I have done a lot of similar work to what you are doing using JQueryUI - it was quite easy in the end.