Drag and Drop


Give your pages interactivity by adding “drag and drop”  Take your star wars or star trek list of movies (just a list, not the responsive layout) and add functionality so that the user can re-order the movies by dragging and dropping them.

This is a test of the model-view-controller architecture and walks you through some functionality built in to HTML.

Where to Learn More


These are suggestions not requirements.

Store your movies as objects in a javascript array.  When a movie is dropped into a new position, update the JavaScript array to reflect the new ordering and then rebuild the HTML displayed as you’ve done before as if a button had been pressed.

Write a method, I called mine “showTheMovies”, which goes through your array of movies in order and writes them to the screen in divs.  Don’t forget to call this function after reordering the movie array.

In each div for each movie, set the div id =”n” where n = the index of the movie in the array.  For example, the first movie in the array is written into a div as follows <div id=”0″ … > Star Wars … </div> (that’s a zero in the quotes, the font is a little unfortunate here).  Later you can use the div id as an index into the array of movies.

Inside a drop event handler, the phrase

var targetID = ev.target.id; 
var $targetBlock = jQuery('#'+ev.target.id);

means the following: Assuming that ev is the event passed into the handler, get the ID of the target and store it in targetID. Then use jQuery to get the block with that id. Store the block in $targetBlock.

In the drag event handler, you might add something like the following


This adds the id of the div being dragged for handy reference later in the drop handler. Then in the drop handler, you can get the block being dragged as:

var sourceID = ev.dataTransfer.getData("id");
var $sourceBlock = jQuery('#'+sourceID);

You can use the sourceID variable as an index into the movies array.

Here’s a starting point for JSON and jQuery from before.

What to do

Modify your JSON assignment so that you can drag a movie to a different place in the list.

Submission Instructions

Same as before:  make a page on your CS account and submit the link through Learning Suite.