HTML5 and CSS3, Second Edition

(singke) #1
html5_dragdrop/javascripts/cards.js
Line 1 if('draggable'indocument.createElement('div')) {


  • }else{


createDragAndDropEvents();




  • Modernizr.load(


(^5) {



addCardClickHandler();

- );


- }








On line 1 we detect support for the draggable element on <div> tags. If it’s sup-
ported, we fire off the createDragAndDropEvents() method. If it’s not supported, we
use Modernizr.load() to bring in jQuery UI.

Once jQuery UI is loaded, we use the sortable() method it provides to turn our
cards region into a sortable region. All of the child elements become sortable.
Take a close look at line 8. That’s one line of code to do what we did with
native Drag and Drop support. Of course, that’s one line of code that we had
to add; we still had to bring in an external library.

jQuery UI has tons of great stuff in it, from date-picker widgets to complex
animations. It’s a huge library, and you might not need everything it includes.
In this example we loaded jQuery UI from a content-delivery network. But in
production, you should create a customized download and include only the
components you need. The jQuery UI website has a tool to help you do that.^12

Even with a fallback, we have one last thing to worry about: accessibility. The
specification doesn’t say anything about how to handle people who can’t use
a mouse. If we implemented drag-and-drop functionality on our interfaces,
we’d need to develop a secondary method that didn’t require JavaScript or a
mouse to work, and that method would depend on what we’re trying to do.
This card sorter we built is completely unusable by a person without sight—
because we didn’t plan for accessibility from the start. We could make our
code more accessible by adding an order field to each card and letting the user
type in a number, and then having a button the user can press to reorder
the cards. That interface might even be nice for sighted users who simply
don’t like the idea of dragging elements around.

12.http://jqueryui.com/download/

report erratum • discuss

Getting It All Sorted Out with Drag and Drop • 237


Download from Wow! eBook <www.wowebook.com>

Free download pdf