Online Book Reader

Home Category

HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [304]

By Root 1500 0
aspect of this program is the inclusion of several draggable elements. This program demonstrates how jQuery simplifies working with a number of elements.

Take a look at the entire program before you see the smaller segments:

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

type = ”text/css”

href = ”css/ui-lightness/jquery-ui-1.8.1.custom.css” />

dragDrop.html

Drag and Drop Demo

Drag me

Drop on me


Building the basic page

As typical with jQuery, the HTML code is simple. It’s very striking that you only see a single dragMe element. It turns out to be simpler to build a single element in HTML and use jQuery and JavaScript to make as many copies as you need. You also see a single target element. I added basic CSS to make the element easy to see (borders) and set them as absolute positioned so that I could control the initial position.

Note that I attached an ID to target (because there will be a single target on the page) and made dragMe a class (because I want to be able to have several draggable elements on the page).


Initializing the page

The initialization is a bit more elaborate than some of the earlier examples in this chapter, but it still isn’t too difficult to follow. The main addition is the ability to respond to some specialty events:

$(init);

function init(){

// make some clones of dragMe

cloneDragMe();

//make all drag me elements draggable

$(“.dragMe”).draggable();

//set target as droppable

$(“#target”).droppable();

//bind events to target

$(“#target”).bind(“drop”, changeTarget);

$(“#target”).bind(“dropout”, resetTarget);

} // end init

The steps here aren’t hard to follow:

1. Make copies of the dragme element.

This part isn’t critical (in fact, I added it after testing with a single element). However, if you want to have multiple copies of the draggable element, use a method to encapsulate the process.

2. Make all dragme elements draggable.

Use the jQuery draggable() method on all elements with the dragMe class.

3. Establish the target as a droppable element.

The droppable() method sets up an element so that it can receive events when a draggable element

Return Main Page Previous Page Next Page

®Online Book Reader