HTML and CSS Reference
In-Depth Information
3.
This code first calls the stopPropagation() function to keep this event from
bubbling up to the parent element. It also calls preventDefault() to cancel the
browser's default action, which as we found out, is to navigate to the image file.
It then gets the id from the dataTransfer object and uses this to access the img
element. This function then creates a new img element and sets all the necessary
properties and adds the necessary event handlers. As I explained before, the drop
event is raised on the target element; the elements being dropped on. The id for
the new img element is computed using the id of the new location, which is obtained
from the target property of the event object. The id prefix (“b” or “w”) is copied
from the existing img element. Finally, this code removes the existing img element.
4.
now you'll need to wire-up the event handlers. To do that, add the following code
shown in bold:
var squares = document.querySelectorAll('.bblack');
var i = 0;
while (i < squares.length) {
var s = squares[i++];
s.addEventListener('dragover', dragOver, false);
s.addEventListener('drop', drop, false);
}
i = 0;
var pieces = document.querySelectorAll('img');
while (i < pieces.length) {
var p = pieces[i++];
p.addEventListener('dragstart', dragStart, false);
}
5.
The dragstart event must be added to the img elements. This code gets all of the
img elements using the querySelectorAll() function.
6.
now press F5 to start the application. You should be able to drag a checker to any
red square.
Providing Visual Feedback
When dragging an element it's a good idea to provide some visual feedback indicating the object that was
selected. By setting the dropEffect property in the dragover event handler the cursor indicates if a drop is
allowed or not. However, you should do more than that. Both the source and target elements should stand
out visually so the user can easily see that if they release the mouse button, the piece will be moved from here
to there.
To do this, you'll dynamically add a class attribute to the source and target elements. Then you can style
them with normal CSS style rules. For the source element you'll use the dragstart and dragend events to add
and then remove the class attribute. Likewise for target element you'll use the dragenter and dragleave events.
 
Search WWH ::




Custom Search