Randomblue
Randomblue

Reputation: 116263

Emulate drag-and-drop using JavaScript

I know that jQuery can programmatically trigger events on DOM elements that are listening to those events. For example $el.click() will trigger a click event on $el without having to physically click $el with the mouse.

Given two DOM elements dom1 and dom2, is it possible to programmatically emulate a drag-and-drop from dom1 to dom2 using jQuery (or vanilla JavaScript), where dom1 is draggable and dom2 is droppable using jQuery UI.

Note: The reason I want to do this is to build automated UI tests.

Upvotes: 5

Views: 5486

Answers (4)

prodigitalson
prodigitalson

Reputation: 60413

If you're using UI then there are events dragstart, drag, and dragstop on the draggable behavior. You should be able to invoke these programmatically by using jQuery.trigger() just like any other event. But, you'd need to manually manipulate the event instance somehow, to input the coordinates for the item to be dropped at. I'm not sure how well that would work, or why you would want to do it.

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

You have to remember that jQuery.trigger does not fire the HTML event, that is, calling .click will not cause a link to be followed. It only triggers events set with jQuery.

http://jupiterjs.com/news/syn-a-standalone-synthetic-event-library is a library that truly mimics HTML events. It's very easy to use

The following asserts that 'hello' has been removed from the page:

Syn.click( {},'hello' )
   .type( 'Hello World' )
   .delay()         //waits 600ms seconds by default
   .drag( $('#trash') , function() {
     ok( $('#hello').length == 0, "removed hello" )
 }); 

Upvotes: 2

Damen TheSifter
Damen TheSifter

Reputation: 911

You want , with animation move to a new parent. Check the function in JQuery - animate moving DOM element to new parent?

Upvotes: 0

netadictos
netadictos

Reputation: 7722

I normally use jquery.ui for complex things with dragging-dropping: http://jqueryui.com/demos/draggable/

Upvotes: -1

Related Questions