3.3 | Drag and Drop |
I'm sure you all know the concept of drag and drop... well using a bit of JavaScript you can drag and drop your layers all around the screen. It's not really an animation of sorts, but you use a similar line of thought.
This drag and drop script, is a combination of 3 functions - down(), move(), and up() - to accomplish the task of clicking a layer, dragging it, and dropping it, respectfully.
drag = 0;
function down(mouse) {
if (drag == 1) {
layerleft = mouse.pageX - document.layers[draglayer].left;
layertop = mouse.pageY - document.layers[draglayer].top;
document.layers[draglayer].zIndex = 1;
window.captureEvents(Event.MOUSEMOVE);
}
}
function move(mouse) {
document.layers[draglayer].left = mouse.pageX - layerleft;
document.layers[draglayer].top = mouse.pageY - layertop;
}
function up() {
window.releaseEvents(Event.MOUSEMOVE);
}
window.onMouseDown = down;
window.onMouseMove = move;
window.onMouseUp = up;
window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
When we click the mouse, the down() function will be called. When we move the mouse, the move() function will be called. And when we release the mouse, the up() function will be called.
The down() function does a little pre-calculation to figure out the difference between where on the layer we have clicked and the position of the layer on the screen. This is important in the move() function which is what actually moves the layer around. But unlike before we don't have to have any loops or anything because the browser will take care of this for us. Every time the mouse is moved even one pixel, the layer will also move one pixel - so you could say this is a "real-time" animation.
We stop the dragging motion by using the window.releaseEvents() method. When someone releases the mouse, the function associated with MOUSEMOVE will immediately stop executing.
<LAYER NAME="layer1" LEFT=100 TOP=100 CLIP="0,0,100,100" BGCOLOR=#FF0000 onMouseOver="draglayer='layer1';drag=1;" onMouseOut="drag=0">
</LAYER>
<LAYER NAME="layer2" LEFT=250 TOP=100 CLIP="0,0,100,100" BGCOLOR=#0000FF onMouseOver="draglayer='layer2';drag=1;" onMouseOut="drag=0">
</LAYER>
Using the onMouseOver and onMouseOut events in our layer tags, we can switch from being in a "draggable mode" or not just by changing the "drag" variable to 1 or 0. In the onMouseOver we also have to pass which layer is going to be dragable.
1.1 Introduction
1.2 Overlapping 1.3 Nesting 1.4 Using JavaScript |
2.1 Sliding Layers
2.2 Pre-Built Functions 2.3 Clipping Layers 2.4 Looping Animations 2.5 Changing Images |
3.1 Mouse-Click Animation
3.2 Capturing Keystrokes 3.3 Drag and Drop 4.1 Making Demos 4.4 Problems 4.5 Screen Sizes |
|