HTML5 and CSS3, Second Edition

(singke) #1
To ensure that dragging and dropping works correctly, we need to prevent
the dragover event from firing, because by default the browser prevents us from
dropping elements onto other elements.^10 So, we add the following code to
our createDragAndDropEvents() function so we can drop cards onto other cards:

html5_dragdrop/javascripts/cards.js
cards.on("dragover",".card",function(event){
event.preventDefault();
return(false);
});

That does it for the main functionality, but we’ve hit a limitation with the way
Drag and Drop and contenteditable work. Elements that are draggable are not
editable. To get around that, we’ll need to remove the draggable attribute from
the card element when the editor gets focus, and add it back when the editor
loses focus. jQuery’s parent() method makes it really easy to grab the card
element.

html5_dragdrop/javascripts/cards.js
cards.on("focus",".editor",function(event){
$(this).parent().removeAttr('draggable');
});

cards.on("blur",".editor",function(event){
$(this).parent().attr('draggable', true);
});

Finally, we fire off our two functions to add the events.


html5_dragdrop/javascripts/cards.js
createDragAndDropEvents();
addCardClickHandler();

We can add cards, edit them, and drag them around to sort them. Of course,
this solution doesn’t work everywhere.

Falling Back


Modernizr can’t help with detection. Internet Explorer 8 supports Drag and
Drop, but it doesn’t support it on anything other than text selection, links,
and images. Thus, although Modernizr correctly detects Drag and Drop sup-
port, it’s not complete support in this case. So, we’ll detect for support by
seeing if the <div> element supports the draggable attribute. If it doesn’t, then
we’ll make things sortable using jQuery UI’s sortable() method.^11

10.https://developer.mozilla.org/en-US/docs/Web/Reference/Events/dragover
11.http://jqueryui.com/sortable/

Chapter 10. Creating Interactive Web Applications • 236


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf