Dragging Elements with onMouseMove : Mouse Event : Event JAVASCRIPT DHTML TUTORIALS


JAVASCRIPT DHTML TUTORIALS » Event » Mouse Event »

 

Dragging Elements with onMouseMove





/*
JavaScript Bible, Fourth Edition
by Danny Goodman 

John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD><TITLE>onMouseMove Event Handler</TITLE>

<STYLE TYPE="text/css">
    #camap {position:absolute; left:20; top:120}
    #ormap {position:absolute; left:80; top:120}
    #wamap {position:absolute; left:140; top:120}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
// global variables used while dragging
var offsetX = 0
var offsetY = 0
var selectedObj
var frontObj
// set document-level event handlers
document.onmousedown = engage
document.onmouseup = release
// positioning an object at a specific pixel coordinate
function shiftTo(obj, x, y) {
    obj.style.pixelLeft = x
    obj.style.pixelTop = y
}
// setting the z-order of an object
function bringToFront(obj) {
    if (frontObj) {
        frontObj.style.zIndex = 0
    }
    frontObj = obj
    frontObj.style.zIndex = 1
}
// set global var to a reference to dragged element
function setSelectedObj() {
    var imgObj = window.event.srcElement
    if (imgObj.id.indexOf("map"== 2) {
        selectedObj = imgObj
        bringToFront(selectedObj)
        return
    }
    selectedObj = null
    return
}
// do the dragging (called repeatedly by onMouseMove)
function dragIt() {
    if (selectedObj) {
        shiftTo(selectedObj, (event.clientX - offsetX)(event.clientY - offsetY))
        return false
    }
}
// set global vars and turn on mousemove trapping (called by onMouseDown)
function engage() {
    setSelectedObj()
    if (selectedObj) {
        document.onmousemove = dragIt
        offsetX = window.event.offsetX - document.body.scrollLeft
        offsetY = window.event.offsetY - document.body.scrollTop
    }
}
// restore everything as before (called by onMouseUp)
function release() {
    if (selectedObj) {
        document.onmousemove = null
        selectedObj = null
    }
}
</SCRIPT>
</HEAD>
<BODY>
<H1>onMouseMove Event Handler</H1>
<HR>
Click and drag the images:
<IMG ID="camap" SRC="http://www.navioo.com/style/logo.png" WIDTH="47" HEIGHT="82" BORDER="0">
<IMG ID="ormap" SRC="http://www.navioo.com/style/logoRed.png" WIDTH="57" HEIGHT="45" BORDER="0">
<IMG ID="wamap" SRC="http://www.navioo.com/style/logo.png" WIDTH="38" HEIGHT="29" BORDER="0">
</SCRIPT>
</BODY>
</HTML>

           
       



-

Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .

Follow Navioo On Twitter

JAVASCRIPT DHTML TUTORIALS

 Navioo Event
» Mouse Event