Enable Drag And Drop Script In Wordpress

27th October 2008 - 3 minutes read time

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".


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.

  1. if ( is_admin() ) {
  2. wp_enqueue_script("scriptaculous-dragdrop");
  3. }

You can now create your sortable list.

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

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

  1. Position.includeScrollOffsets = true;
  2. Sortable.create('container_sortable',{
  3. tag: 'div',
  4. scroll: window,
  5. onChange: doSomething
  6. });
  8. function doSomething(){
  9. // on change code here
  10. }

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.