Enable Drag And Drop Script In Wordpress

Note: This code has been written with WordPress 2.8 in mind. It won't work on versions prior to 2.6 and might have unpredictable results in later versions.

Drag and drop is a useful mechanism to do stuff and can turn a complicated set of buttons or drop down lists into a simple elegant solution.

Wordpress has lots of scripts built in, which do a lot of useful functions. However, they are not enabled by default, which means that in order to get your script to work you need to enable them.

The drag and drop functionality in Wordpress is provided by the Scriptaculous framework. To get Wordpress to include this in your page header just use the function wp_enqueue_script() with the parameter "scriptaculous-dragdrop".

wp_enqueue_script("scriptaculous-dragdrop");

I have had limited success running this code from within functions, so your best bet is to add it to the bottom of your plugin file, outside the scope of any functions.

If you only want to enable them in the admin section the enclose this function call in an if statement that uses the is_admin() function to see if the script is being run in the admin section.

if ( is_admin() ) {
  wp_enqueue_script("scriptaculous-dragdrop");
}

You can now create your sortable list.

<div id="container_sortable">
<div id="item_1">Item 1</div>
<div id="item_2">Item 2</div>
<div id="item_3">Item 3</div>
</div>

And add the JavaScript to get it working. The following code converts the above elements into a sortable list.

Position.includeScrollOffsets = true;
Sortable.create('container_sortable',{
    tag: 'div',
    scroll: window,
    onChange: doSomething
});

function doSomething(){
  // on change code here
}

Note that the id format of "item_itemNumber" as in "item_1" is important to get Sortable class functions like sequence() working. If the items are not in this format then sequence() will return null for that item.

The line Position.includeScrollOffsets = true; is added before the call to Sortable.create() in order to get window scrolling working. If you have a large list, and you want items dragged to the top of the window to scroll upwards then use this and the option "scroll: window" to create a browser compatible mechanism of scrolling the window.

For a full list of the sort of scripts that can include see the bottom of the Wordpress page on wp_enqueue_script.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.