JavaScript DHTML/Event/Mouse Event

Материал из Web эксперт
Перейти к: навигация, поиск

Содержание

Called from an onmousedown event handler

   <source lang="html4strict">
 

/* Examples From JavaScript: The Definitive Guide, Fourth Edition Legal matters: these files were created by David Flanagan, and are Copyright (c) 2001 by David Flanagan. You may use, study, modify, and distribute them for any purpose. Please note that these examples are provided "as-is" and come with no warranty of any kind. David Flanagan

  • /

/**

* PortableDrag.js:
* beginDrag() is designed to be called from an onmousedown event handler.
* elementToDrag may be the element that received the mousedown event, or it
* may be some containing element.  event must be the Event object for the
* mousedown event.  This implementation works with both the DOM Level 2
* event model and the IE Event model.
**/

function beginDrag(elementToDrag, event) {

   // Compute the distance between the upper-left corner of the element
   // and the mouse click. The moveHandler function below needs these values.
   var deltaX = event.clientX - parseInt(elementToDrag.style.left);
   var deltaY = event.clientY - parseInt(elementToDrag.style.top);
   // Register the event handlers that will respond to the mousemove events
   // and the mouseup event that follow this mousedown event.  
   if (document.addEventListener) {  // DOM Level 2 Event Model
 // Register capturing event handlers
       document.addEventListener("mousemove", moveHandler, true);
 document.addEventListener("mouseup", upHandler, true);
   }
   else if (document.attachEvent) {  // IE 5+ Event Model
 // In the IE Event model, we can"t capture events, so these handlers
 // are triggered when only if the event bubbles up to them.
 // This assumes that there aren"t any intervening elements that
 // handle the events and stop them from bubbling.
 document.attachEvent("onmousemove", moveHandler);
 document.attachEvent("onmouseup", upHandler);
   }
   else {                            // IE 4 Event Model
 // In IE 4 we can"t use attachEvent(), so assign the event handlers
 // directly after storing any previously assigned handlers so they 
       // can be restored.  Note that this also relies on event bubbling.
 var oldmovehandler = document.onmousemove;
 var olduphandler = document.onmouseup;
 document.onmousemove = moveHandler;
 document.onmouseup = upHandler;
   }
   // We"ve handled this event.  Don"t let anybody else see it.  
   if (event.stopPropagation) event.stopPropagation();   // DOM Level 2
   else event.cancelBubble = true;                       // IE
   // Now prevent any default action.
   if (event.preventDefault) event.preventDefault();     // DOM Level 2
   else event.returnValue = false;                       // IE
   /**
    * This is the handler that captures mousemove events when an element
    * is being dragged.  It is responsible for moving the element.
    **/
   function moveHandler(e) {
 if (!e) e = window.event;  // IE event model
       // Move the element to the current mouse position, adjusted as
 // necessary by the offset of the initial mouse click.
 elementToDrag.style.left = (e.clientX - deltaX) + "px";
 elementToDrag.style.top = (e.clientY - deltaY) + "px";
 // And don"t let anyone else see this event.
 if (e.stopPropagation) e.stopPropagation();       // DOM Level 2
 else e.cancelBubble = true;                       // IE
   }
   /**
    * This is the handler that captures the final mouseup event that
    * occurs at the end of a drag.
    **/
   function upHandler(e) {
 if (!e) e = window.event;  // IE event model
 // Unregister the capturing event handlers.
 if (document.removeEventListener) {    // DOM Event Model
     document.removeEventListener("mouseup", upHandler, true);
     document.removeEventListener("mousemove", moveHandler, true);
 }
 else if (document.detachEvent) {       // IE 5+ Event Model
     document.detachEvent("onmouseup", upHandler);
     document.detachEvent("onmousemove", moveHandler);
 }
 else {                                 // IE 4 Event Model
     document.onmouseup = olduphandler;
     document.onmousemove = oldmovehandler;
 }
 // And don"t let the event propagate any further.
 if (e.stopPropagation) e.stopPropagation();       // DOM Level 2
 else e.cancelBubble = true;                       // IE
   }

}



 </source>
   
  


Catches and manages the mouse"s events

   <source lang="html4strict">
 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML>

 <HEAD>
   <TITLE>JsLib 1.3 - Exemple - souris.js</TITLE>
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
   <META NAME="Author" CONTENT="Etienne CHEVILLARD">
   
   <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">

/* souris.js

* Role : capture et gere les evenements souris
* Projet : JsLib
* Auteur : Etienne CHEVILLARD (echevillard@users.sourceforge.net)
* Version : 1.3
* Creation : 20/08/2001
* Mise a jour : 23/02/2005
* Bogues connues : - Netscape Navigator 4 ne gere pas le bouton du milieu
*/

// capture les evenements sous Netscape Navigator if (document.layers) {

 document.captureEvents(Event.MOUSEDOWN);
 document.captureEvents(Event.MOUSEUP);
 document.captureEvents(Event.MOUSEMOVE);

} // --- Fonctions --- // retourne vrai si le dernier clic de souris concerne le bouton droit function boutonDroit(e) {

 if (window.event)
   return (window.event.button==2);
 else
   return (e.which==3);

} // fin boutonDroit(e) // retourne vrai si le dernier clic de souris concerne le bouton gauche function boutonGauche(e) {

 if (window.event)
   return (window.event.button==1);
 else {
   if (e.type=="mousemove")
     return (false);
   else
     return (e.which==1);
 }

} // fin boutonGauche(e) // retourne vrai si le dernier clic de souris concerne le bouton du milieu function boutonMilieu(e) {

 if (window.event)
   return ((window.event.button==3) || (window.event.button==4));
 else
   return (e.which==2);

} // fin boutonMilieu(e) // retourne la position horizontale a l"ecran du pointeur de la souris function pointeurEcranX(e) {

 if (window.event)
   return (window.event.screenX);
 else
   return(e.screenX);

} // fin pointeurEcranX(e) // retourne la position verticale a l"ecran du pointeur de la souris function pointeurEcranY(e) {

 if (window.event)
   return (window.event.screenY);
 else
   return(e.screenY);

} // fin pointeurEcranY(e) // retourne la position horizontale sur la page du pointeur de la souris function pointeurX(e) {

 if (window.event)
   return (window.event.clientX);
 else
   return(e.pageX);

} // fin pointeurX(e) // retourne la position verticale sur la page du pointeur de la souris function pointeurY(e) {

 if (window.event)
   return (window.event.clientY);
 else
   return(e.pageY);

} // fin pointeurY(e)

   </SCRIPT>
 </HEAD>
 <BODY>

JsLib 1.3


Exemple - souris.js

   <NOSCRIPT>

Erreur : votre navigateur ne reconnait pas le Javascript ou est configuré pour ne pas prendre en compte le code Javascript. Dans ce dernier cas, vous pouvez modifier la configuration dans les préférences/options de votre navigateur.


   </NOSCRIPT>
   <FORM ACTION="GET" NAME="f1" onSubmit="return false">
     <P>Déplacez la souris sur la page et cliquez où vous le souhaitez.
           Type de l"événement : 
           <INPUT TYPE="radio" NAME="r1"> Déplacement du pointeur (mousemove)
<INPUT TYPE="radio" NAME="r1"> Bouton de souris enfoncé (mousedown)
<INPUT TYPE="radio" NAME="r1"> Bouton de souris relaché (mouseup)
           Bouton concerné : 
           <INPUT TYPE="checkbox" NAME="c1"> Bouton gauche
<INPUT TYPE="checkbox" NAME="c2"> Bouton du milieu
<INPUT TYPE="checkbox" NAME="c3"> Bouton droit

Position du pointeur sur la page (coordonnées en pixels) :  X= <INPUT TYPE="text" NAME="t1" SIZE=5 VALUE=""> Y= <INPUT TYPE="text" NAME="t2" SIZE=5 VALUE=""> <P>Position du pointeur à l"écran (coordonnées en pixels) :  X= <INPUT TYPE="text" NAME="t3" SIZE=5 VALUE=""> Y= <INPUT TYPE="text" NAME="t4" SIZE=5 VALUE=""> </TD></TR></TABLE> </FORM> <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript"> document.onmousemove = pointeurDeplace; function pointeurDeplace(e) { document.f1.r1[0].checked = true; majFormulaire(e); } document.onmousedown = boutonEnfonce; function boutonEnfonce(e) { document.f1.r1[1].checked = true; majFormulaire(e); } document.onmouseup = boutonRelache; function boutonRelache(e) { document.f1.r1[2].checked = true; majFormulaire(e); } function majFormulaire(e) { document.f1.t1.value = pointeurX(e); document.f1.t2.value = pointeurY(e); document.f1.t3.value = pointeurEcranX(e); document.f1.t4.value = pointeurEcranY(e); document.f1.c1.checked = boutonGauche(e); document.f1.c2.checked = boutonMilieu(e); document.f1.c3.checked = boutonDroit(e); } </SCRIPT> </BODY> </HTML> </source>

Codependent Link Tag and the onMouseOver Event

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>onMouseOver Event</TITLE> </HEAD> <BODY>

<A HREF="http://www.wbex.ru" onMouseOver="this.href="I cannot let you go.";"> Please do not leave me!</A>

</BODY> </HTML>


 </source>
   
  


Creating a Rollover Effect

   <source lang="html4strict">
 

/* Learn How to Program Using Any Web Browser by Harold Davis Apress CopyRight 2004 ISBN: 1590591135

  • /

<HTML> <HEAD> <TITLE>Visualize Your Butterfly!</TITLE> </HEAD> <BODY>

Visualize Your Butterfly!

Pass your mouse over a pattern to see the butterfly wearing it!

<IMG src="white.gif" height=100 width=175 border=0>

<IMG src="http://www.wbex.ru/style/logo.png" height=75 width=75 border=2

     onMouseOver="document.images[0].src="http://www.wbex.ru/style/logo.png""; 
     onMouseOut="document.images[0].src="http://www.wbex.ru/style/logoRed.png";">

<IMG src="http://www.wbex.ru/style/logo.png" height=75 width=75 border=2

     onMouseOver="document.images[0].src="http://www.wbex.ru/style/logo.png";" 
     onMouseOut="document.images[0].src="white.gif";">

<IMG src="http://www.wbex.ru/style/logo.png" height=75 width=75 border=2

     onMouseOver="document.images[0].src="http://www.wbex.ru/style/logo.png";" 
     onMouseOut="document.images[0].src="http://www.wbex.ru/style/logoRed.png";">

<IMG src="http://www.wbex.ru/style/logo.png" height=75 width=75 border=2

     onMouseOver="document.images[0].src="http://www.wbex.ru/style/logo.png";" 
  onMouseOut="document.images[0].src="http://www.wbex.ru/style/logoRed.png";">

</BODY> </HTML>


 </source>
   
  


Cursor Arrival and Departure

   <source lang="html4strict">
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">

<html> <head> <title>Mouse roll over</title> <style type="text/CSS"> .direction {background-color:#00ffff;

            width:100px; 
            height:50px; 
            text-align:center
           }
  1. main {background-color:#fff6666; text-align:center}

html {background-color:#cccccc} body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px;

   margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}

h1 {text-align:right; font-size:1.5em; font-weight:bold} h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline} .buttons {margin-top:10px}

</style> <script type="text/javascript"> function showArrival(evt) {

   var direction = "";
   evt = (evt) ? evt : ((window.event) ? event : null);
   if (evt) {
       var elem = (evt.target) ? evt.target : ((evt.srcElement) ? 
           evt.srcElement : null);
       if (elem) {
           // limit processing to element nodes
           if (elem.nodeType == 1) {
               // for W3C DOM property
               if (evt.relatedTarget) {
                   if (evt.relatedTarget != elem.firstChild) {
                       direction = (evt.relatedTarget.firstChild) ? 
                           evt.relatedTarget.firstChild.nodeValue : "parts unknown";
                   }
               // for IE DOM property
               } else if (evt.fromElement) {
                   direction = (event.fromElement.innerText) ? 
                      event.fromElement.innerText : "parts unknown";
               }
               // display results
               document.getElementById("direction").value = "Arrived from: " + 
                   direction;
           }
       }
   }

} function showDeparture(evt) {

   var direction = "";
   evt = (evt) ? evt : ((window.event) ? event : null);
   if (evt) {
       var elem = (evt.target) ? evt.target : ((evt.srcElement) ? 
           evt.srcElement : null);
       if (elem) {
            // limit processing to element nodes
            if (elem.nodeType == 1) {
               // for W3C DOM property
               if (evt.relatedTarget) {
                   if (evt.relatedTarget != elem.firstChild) {
                       direction = (evt.relatedTarget.firstChild) ? 
                           evt.relatedTarget.firstChild.nodeValue : "parts unknown";
                   }
               // for IE DOM property
               } else if (evt.toElement) {
                   direction = (event.toElement.innerText) ? 
                       event.toElement.innerText : "parts unknown";
               }
               // display results
              document.getElementById("direction").value = "Departed to: " + 
                  direction;
           }
       }
   }

} </script> </head> <body>

Cursor Arrival/Departure


North
West Roll East
South

<form name="output"> <input id="direction" type="text" size="30" /> </form> </body> </html>


 </source>
   
  


Cutting and Pasting under Script Control

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>onBeforeCut and onCut Event Handlers</TITLE> <STYLE TYPE="text/css"> TD {text-align:center} TH {text-decoration:underline} .blanks {text-decoration:underline} </STYLE> <SCRIPT LANGUAGE="JavaScript"> function selectWhole() {

   var obj = window.event.srcElement
   var range = document.body.createTextRange()
   range.moveToElementText(obj)
   range.select()
   event.returnValue = false

} function handleCut() {

   var rng = document.selection.createRange()
   clipboardData.setData("Text",rng.text)
   var elem = event.srcElement
   elem.innerText = ""
   event.returnValue = false

} function handlePaste() {

   var elem = window.event.srcElement
   if (elem.className == "blanks") {
       elem.innerHTML = clipboardData.getData("Text")
   }
   event.returnValue = false

} function handleBeforePaste() {

   var elem = window.event.srcElement
   if (elem.className == "blanks") {
       event.returnValue = false
   }

} </SCRIPT> </HEAD> <BODY>

onBeforeCut and onCut Event Handlers


<P>Your goal is to cut and paste one noun and one adjective from the following table into the blanks of the sentence. Select a word from the table and use the Edit or context menu to cut it from the table. Select one or more spaces of the blanks in the sentence and choose Paste to replace the blank with

the clipboard contents.

NounsAdjectives
truckround
dollred
ballpretty

Pat said, "Oh my, the       is so      !"

<BUTTON onClick="location.reload()">Reset</BUTTON> </BODY> </HTML>



 </source>
   
  


Dragging Elements with onMouseMove

   <source lang="html4strict">
 

/* 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>

onMouseMove Event Handler


Click and drag the images: <IMG ID="camap" SRC="http://www.wbex.ru/style/logo.png" WIDTH="47" HEIGHT="82" BORDER="0"> <IMG ID="ormap" SRC="http://www.wbex.ru/style/logoRed.png" WIDTH="57" HEIGHT="45" BORDER="0"> <IMG ID="wamap" SRC="http://www.wbex.ru/style/logo.png" WIDTH="38" HEIGHT="29" BORDER="0"> </SCRIPT> </BODY> </HTML>


 </source>
   
  


Get component From Point (Mouse)

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>componentFromPoint() Method</TITLE> <SCRIPT LANGUAGE="JavaScript"> function whereInWorld(elem) {

   var x = event.clientX
   var y = event.clientY
   var component = document.all.myTextarea.ruponentFromPoint(x,y)
   if (window.event.srcElement == document.all.myTextarea) {
       if (component == "") {
           status = "mouseDown event occurred inside the element"
       } else {
           status = "mouseDown occurred on the element\"s " + component
       }
   } else {
       status = "mouseDown occurred " + component + " of the element"
   }

} </SCRIPT> </HEAD> <BODY onMouseDown="whereInWorld()">

componentFromPoint() Method


Tracking the mouseDown event relative to the textarea object. View results in status bar.

<FORM> <TEXTAREA NAME="myTextarea" WRAP="off" COLS=12 ROWS=4> This is Line 1 This is Line 2 This is Line 3 This is Line 4 This is Line 5 This is Line 6 </TEXTAREA> </FORM> </BODY> </HTML>


 </source>
   
  


Get mouse position in mouse down event (IE)

   <source lang="html4strict">
 

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> function clicked() {

   window.status = "X = " + event.x + " Y = " + event.y

} </script> </head> <body onmousedown="clicked()"> </body> </html>


 </source>
   
  


Get mouse position with on mouse move event (IE)

   <source lang="html4strict">
 

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> function moved() {

   window.status = "X = " + event.x + " Y = " + event.y
   follower.style.pixelTop = event.y
   follower.style.pixelLeft = event.x

} </script> </head> <body onmousemove="moved()">

Squeak!

</body> </html>


 </source>
   
  


H1 double click events

   <source lang="html4strict">
 

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> function addunderline() {

   head1.style.textDecoration = "underline"

} function removeunderline() {

   head1.style.textDecoration = "none"

} function addoverline() {

   head1.style.textDecoration = "overline"

} function addlinethrough() {

   head1.style.textDecoration = "line-through"

} </script> </head> <body>

Welcome to this page!

</body> </html>


 </source>
   
  


Image Mouse on and out

   <source lang="html4strict">
 

<HTML> <HEAD> <SCRIPT language="JavaScript">

</SCRIPT> </HEAD> <BODY> <A HREF="#" onMouseOver="change_it("pic1")" onMouseOut="change_back("pic1")"><IMG SRC="http://www.wbex.ru/style/logo.png" name="pic1" id="pic1" border="0"></A>

<A HREF="#" onMouseOver="change_it("pic2")" onMouseOut="change_back("pic2")"><IMG SRC="http://www.wbex.ru/style/logo.png" name="pic2" id="pic2" border="0"></A> <P> <A HREF="#" onMouseOver="change_it("pic3")" onMouseOut="change_back("pic3")"><IMG SRC="http://www.wbex.ru/style/logo.png" name="pic3" id="pic3" border="0"></A> <P> <A HREF="#" onMouseOver="change_it("pic4")" onMouseOut="change_back("pic4")"><IMG SRC="http://www.wbex.ru/style/logo.png" name="pic4" id="pic4" border="0"></A> </BODY> </HTML> </source>

Mouse and key event (IE)

   <source lang="html4strict">
 

/* JavaScript Application Cookbook By Jerry Bradenbaugh Publisher: O"Reilly Series: Cookbooks ISBN: 1-56592-577-7

  • /

<HTML> <HEAD>

 <TITLE>Mouse and key event (IE)</TITLE>

<SCRIPT LANGUAGE="JavaScript1.1"> // events.js var keys = ""; var change = true; var x1, x2, y1, y2; // This function enables and disables the // onmousemove event handler of both // Navigator and MSIE function enableEffects(ev) {

 if(change) { 
   if(document.layers) {
     x1 = ev.screenX;
     y1 = ev.screenY;
     document.captureEvents(Event.MOUSEMOVE);  
     }
   else { 
     x1 = event.screenX;
     y1 = event.screenY;
     }
     document.onmousemove = showXY;
   }
 else { 
   if (document.layers) { 
     x2 = ev.screenX;
     y2 = ev.screenY;      
     document.releaseEvents(Event.MOUSEMOVE); 
     }
   else { 
     x2 = event.screenX;
     y2 = event.screenY;
     document.onmousemove = null; 
     }
   window.status = "Start: (" + x1 + "," + y1 + 
     ")  End: (" + x2 + "," + y2 + ")  Distance: " + 
     (Math.abs((x2 - x1) + (y2 - y1))) + " pixels";
   }
 change = !change;
 }

// This function alerts a string of keys that the user has typed function showKeys() {

 if (keys != "") { 
   alert("You have typed: " + keys);
   window.status = keys = ""; 
   }
 else { alert("You have to type some keys first."); }
 }

// This function displays the keys pressed in the status bar function showXY(ev) {

 if (document.all) { ev = event; } 
 window.status = "X: " + ev.screenX + " Y: " + ev.screenY;
 }

// This function captures the keys pressed one at a time function keepKeys(ev) {

 if (document.layers) { 
   keys += String.fromCharCode(ev.which); 
   window.status = "Key pressed: " + String.fromCharCode(ev.which);
   } 
 else { 
   keys += String.fromCharCode(event.keyCode); 
   window.status = "Key pressed: " + String.fromCharCode(event.keyCode);    
   }
 }

</SCRIPT> <SCRIPT LANGUAGE="JavaScript1.1">

</SCRIPT> </HEAD> <BODY BGCLOR=WHITE> Click your mouse button, then move it around, click again to stop tracking.





Now type some keys.... any keys. Then press Show Keys
<FORM><INPUT TYPE=BUTTON VALUE="Show Keys" onClick="showKeys();"></FORM> </BODY> </HTML>



 </source>
   
  


Mouse cross hairs

   <source lang="html4strict">
 

//Crosshairs - http://www.btinternet.ru/~kurt.grigg/javascript /* Paste this link as the last thing on your page, just before </body></html> <script type="text/javascript" src="crosshairs.js"></script> To edit the colour, right click on the crosshairs.js file icon and choose edit. Avoid using a tiled background image. It causes strange CPU strain in Opera.

  • /

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>CrossHairs</title> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <meta http-equiv="content-script-type" content="text/javascript"> <meta http-equiv="content-style-type" content="text/css">

<style type="text/css">

</style> </head> <body> <script type="text/javascript"> //Crosshairs - http://www.btinternet.ru/~kurt.grigg/javascript if ((document.getElementById) && window.addEventListener || window.attachEvent){ (function(){ var hairCol = "#ff0000"; var d = document; var my = -10; var mx = -10; var r; var vert = ""; var hori = ""; var idx = document.getElementsByTagName("div").length;

var thehairs = "
<\/div>" +"
<\/div>";

document.write(thehairs); var pix = "px"; var domWw = (typeof window.innerWidth == "number"); var domSy = (typeof window.pageYOffset == "number"); if (domWw) r = window; else{

 if (d.documentElement && 
 typeof d.documentElement.clientWidth == "number" && 
 d.documentElement.clientWidth != 0)
 r = d.documentElement;
else{ 
 if (d.body && 
 typeof d.body.clientWidth == "number")
 r = d.body;
}

}

function hairs(){ if (domWw){

vert.height = r.innerHeight - 2 + pix;
hori.width = "100%";
}

else{

vert.height = r.clientHeight - 2 + pix;
hori.width = r.clientWidth + pix;
}

}

function scrl(yx){ var y,x; if (domSy){

y = r.pageYOffset;
x = r.pageXOffset;
}

else{

y = r.scrollTop;
x = r.scrollLeft;
}

return (yx == 0)?y:x; }

function mouse(e){ var msy = (domSy)?window.pageYOffset:0; if (!e) e = window.event;

if (typeof e.pageY == "number"){
 my = e.pageY - 5 - msy;
 mx = e.pageX - 4;
}
else{
 my = e.clientY - 6 - msy;
 mx = e.clientX - 6;
}

vert.top = scrl(0) + pix; vert.left = mx + pix; hori.top = my + scrl(0) + pix; }

function ani(){ vert.top = scrl(0) + pix; hori.top = my + scrl(0) + pix; setTimeout(ani,300); }

function init(){ vert = document.getElementById("ver"+idx).style; hori = document.getElementById("hor"+idx).style; hairs(); ani(); } if (window.addEventListener){

window.addEventListener("load",init,false);
window.addEventListener("resize",hairs,false);
document.addEventListener("mousemove",mouse,false);

} else if (window.attachEvent){

window.attachEvent("onload",init);
window.attachEvent("onresize",hairs);
document.attachEvent("onmousemove",mouse);

} })(); }//End. </script> </body> </html>



 </source>
   
  


Mousedown event handler of an object within a Layer

   <source lang="html4strict">
 

/* Examples From JavaScript: The Definitive Guide, Fourth Edition Legal matters: these files were created by David Flanagan, and are Copyright (c) 2001 by David Flanagan. You may use, study, modify, and distribute them for any purpose. Please note that these examples are provided "as-is" and come with no warranty of any kind. David Flanagan

  • /

<script> /**

* This function is intended for use in a mousedown event handler of an object
* within a Layer.  The first argument must be a Layer object.  The second
* argument must be the Event object for the mousedown event.
**/

function beginDrag(layerToDrag, event) {

   // This nested function responds to mousemove events and moves the layer.
   function moveHandler(event) {
 // Move the element to the current mouse position, adjusted as
 // necessary by the offset of the initial mouse click.
 layerToDrag.moveTo(event.pageX - deltaX, event.pageY-deltaY);
 // Don"t take any default action, and don"t propagate further.
 return false;
   }
   // This nested function handles mouseup events.
   // It stops capturing events, and de-register the handlers.
   function upHandler(event) {
 // Stop capturing and handling drag events
 document.releaseEvents(Event.MOUSEMOVE | Event.MOUSEUP);
 document.onmousemove = null;
 document.onmouseup = null;
 // Don"t take any default action, and don"t propagate further.
 return false;
   }
   // Compute the distance between the upper left of the layer and and the
   // mouse click. The moveHandler function below needs these values.
   var deltaX = event.pageX - layerToDrag.left;
   var deltaY = event.pageY - layerToDrag.top;
   // Arrange to capture mousemove and mouseup events.
   // Then arrange to handle them using the functions defined below.
   document.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
   document.onmousemove = moveHandler;
   document.onmouseup = upHandler;

} </script>


<img src="images/plus.gif" width="20" height="20"

    onmousedown="if (event.modifiers & Event.SHIFT_MASK)
                     beginDrag(window.document.div1, event);">



 </source>
   
  


Mouse Drag and Drop

   <source lang="html4strict">
 

//Drag and Drop script - http://www.btinternet.ru/~kurt.grigg/javascript /* 1: Put this style sheet and the dragdrop.js link between the head tags of your page html.

  IMPORTANT! Do not remove "position : relative;" from the dragclass style.

<style type="text/css"> .dragclass{ position : relative; cursor : move; } </style> <script type="text/javascript" src="dragdrop.js"></script>

2: To apply drag and drop status to something just give it the dragclass.

Example:
<p class="dragclass" style="color:red">
Blah blah 
</p>
  • /

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Drag and Drop</title> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <meta http-equiv="content-script-type" content="text/javascript"> <meta http-equiv="content-style-type" content="text/css">

<style type="text/css"> .dragclass{ position : relative; cursor : move; } </style>

<script type="text/javascript"> //Drag and Drop script - http://www.btinternet.ru/~kurt.grigg/javascript if (document.getElementById){ (function(){ //Stop Opera selecting anything whilst dragging. if (window.opera){ document.write("<input type="hidden" id="Q" value=" ">"); } var n = 500; var dragok = false; var y,x,d,dy,dx; function move(e){ if (!e) e = window.event;

if (dragok){
 d.style.left = dx + e.clientX - x + "px";
 d.style.top  = dy + e.clientY - y + "px";
 return false;
}

} function down(e){ if (!e) e = window.event; var temp = (typeof e.target != "undefined")?e.target:e.srcElement; if (temp.tagName != "HTML"|"BODY" && temp.className != "dragclass"){

temp = (typeof temp.parentNode != "undefined")?temp.parentNode:temp.parentElement;
}

if (temp.className == "dragclass"){

if (window.opera){
 document.getElementById("Q").focus();
}
dragok = true;
temp.style.zIndex = n++;
d = temp;
dx = parseInt(temp.style.left+0);
dy = parseInt(temp.style.top+0);
x = e.clientX;
y = e.clientY;
document.onmousemove = move;
return false;
}

} function up(){ dragok = false; document.onmousemove = null; } document.onmousedown = down; document.onmouseup = up; })(); }//End. </script>

</head> <body>


<p class="dragclass" style="top:0px;left:0px;width:200px;text-align:center;background-color:#ff0000;color:#ffffff"> P tag </p>

Div: Relative position

<p>.</p>

<img src="http://www.wbex.ru/style/logo.png" class="dragclass" style="top:0px;left:0px;height:100px;width:150px;padding:0px"/> <p>.<p>

B tag

<img src="http://www.wbex.ru/style/logoRed.png" class="dragclass" style="position:absolute;top:400px;left:200px;height:105px;width:150px;padding:0px"/>

Div: Absolute position

</body> </html>


 </source>
   
  


Mouse in image and out

   <source lang="html4strict">
 

/* JavaScript Application Cookbook By Jerry Bradenbaugh Publisher: O"Reilly Series: Cookbooks ISBN: 1-56592-577-7

  • /

<HTML> <HEAD> <TITLE>Mouse in image and out</TITLE> <SCRIPT LANGUAGE="JavaScript1.1">

</SCRIPT> <SCRIPT LANUAGE="JavaScript"> // images.js // Set image variables var imgPath = "images/"; var arrayHandles = new Array("out", "over"); // Dynamically create image arrays for (var i = 0; i < arrayHandles.length; i++) {

 eval("var " + arrayHandles[i] + " = new Array()");
 }

// Preload the images for (var i = 0; i < imgNames.length; i++) {

 imagePreLoad(imgNames[i], i);
 }

// Define a function to preload the images function imagePreLoad(imgName, idx) {

 for(var j = 0; j < arrayHandles.length; j++) {
   eval(arrayHandles[j] + "[" + idx + "] = new Image()");
   eval(arrayHandles[j] + "[" + idx + "].src = "" + imgPath + imgName + arrayHandles[j] + ".gif"");
   }
 }

// Perform the image rollovers function imageSwap(imagePrefix, imageIndex, arrayIdx) {

 document[imagePrefix].src = eval(arrayHandles[arrayIdx] + "[" + imageIndex + "].src");
 }

// This function displays the text passed in the browser status bar function display(stuff) { window.status = stuff; } </SCRIPT> </HEAD> <BODY BGCOLOR=FFFFEE> <A HREF="javascript: void(0);"

    onMouseOver="imageSwap("img", 0, 1); display(""); return true;"
    onMouseOut="imageSwap("img", 0, 0); display("");">

<IMG SRC="http://www.wbex.ru/style/logo.png"

    NAME=img
    WIDTH=90
    HEIGHT=50
    BORDER=0></A>

</BODY> </HTML>


 </source>
   
  


Mouse over event

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>title Property</TITLE> <SCRIPT LANGUAGE="JavaScript"> var count = 0 function setToolTip(elem) {

   elem.title = "You have previously rolled atop this paragraph " + count + " time(s)."

} function incrementCount(elem) {

   count++;
   setToolTip(elem);

} </SCRIPT> </HEAD> <BODY>

title Property Lab


<P ID="myP" TITLE="First Time!" onMouseOver="incrementCount(this)"> Roll the mouse over this paragraph a few times.
Then pause it to view the tooltip.</P> </BODY> </HTML>


 </source>
   
  


Register mouse down event(IE)

   <source lang="html4strict">
 

<html> <head> <title>X/Y Marks the Spot</title> <script type="text/javascript"> function mouseDown() {

 var locString = "X = " + window.event.screenX + " Y = " + window.event.screenY;
 document.write(locString);

} document.onmousedown=mouseDown; </script> </head> <body> </body> </html>


 </source>
   
  


Return boolean value for on click event

   <source lang="html4strict">
 

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> function sendMe() {

   return confirm("Continue?");

} function chkForm() {

   if (form1.textField.value == "")
   {
       alert("Please fill in the text box");
       form1.textField.focus();
       return false;
   }

} </script> </head> <body> <form name="form1" method="POST" action="youtCGI.cgi" onSubmit="return sendMe()"> <p><input type="text" name="textField"> <input type="submit" value="Submit" onClick="return chkForm()"> <input type="reset" value="Reset"></p> </form> </body> </html>


 </source>
   
  


The onBeforeCopy Event Handler

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>onBeforeCopy Event Handler</TITLE> <SCRIPT LANGUAGE="JavaScript"> function selectWhole() {

   var obj = window.event.srcElement
   var range = document.body.createTextRange()
   range.moveToElementText(obj)
   range.select()
   event.returnValue = false

} </SCRIPT> </HEAD> <BODY>

onBeforeCopy Event Handler


<P>Select one or more characters in the following paragraph. Then execute a Copy command via Edit or context menu.</P> <P ID="myP" onBeforeCopy="selectWhole()">Lorem ipsum dolor sit amet, consectetaur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim adminim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</P> <FORM> <P>Paste results here:
<TEXTAREA NAME="output" COLS="60" ROWS="5"></TEXTAREA> </P> </FORM> </BODY> </HTML>



 </source>
   
  


Use Mouse over action to transfer url location

   <source lang="html4strict">
 

<HTML> <BODY> <FORM> <INPUT type="button" value="Change Status!" onClick="window.status="Hey there!";"> <INPUT type="button" value="Clear Status!" onClick="window.status="";"> </FORM> <A HREF="noplace" onMouseOver="window.location="http://www.wbex.ru";">Mouse over to navigate</A> </BODY> </HTML>


 </source>
   
  


Using Drag-Related Event Handlers

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Dragging Event Handlers</TITLE> <STYLE TYPE="text/css"> TD {text-align:center} TH {text-decoration:underline} .blanks {text-decoration:underline} </STYLE> <SCRIPT LANGUAGE="JavaScript"> var timer function setupDrag() {

   if (event.srcElement.tagName != "TD") {
       // don"t allow dragging for any other elements
       event.returnValue = false
   } else {
       // setup array of data to be passed to drop target
       var passedData = [event.srcElement.innerText, event.srcElement.className]
       // store it as a string
       event.dataTransfer.setData("Text", passedData.join(":"))
       event.dataTransfer.effectAllowed = "copy"
       timer = new Date()
   }

} function timeIt() {

   if (event.srcElement.tagName == "TD" && timer) {
       if ((new Date()) - timer > 2000) {
           alert("Sorry, time is up. Try again.")
           timer = 0
       }
   }

} function handleDrop() {

   var elem = event.srcElement
   var passedData = event.dataTransfer.getData("Text")
   var errMsg = ""
   if (passedData) {
       // reconvert passed string to an array
       passedData = passedData.split(":")
       if (elem.id == "blank1") {
           if (passedData[1] == "noun") {
               event.dataTransfer.dropEffect = "copy"
               event.srcElement.innerText = passedData[0]
           } else {
               errMsg = "You can"t put an adjective into the noun placeholder."
           }
       } else if (elem.id == "blank2") {
           if (passedData[1] == "adjective") {
               event.dataTransfer.dropEffect = "copy"
               event.srcElement.innerText = passedData[0]
           } else {
               errMsg = "You can"t put a noun into the adjective placeholder."
           }
       }
       if (errMsg) {
           alert(errMsg)
       }
   }

} function cancelDefault() {

   if (event.srcElement.id.indexOf("blank") == 0) {
       event.dataTransfer.dropEffect = "copy"
       event.returnValue = false
   }

} </SCRIPT> </HEAD> <BODY onDragStart="setupDrag()" onDrag="timeIt()">

Dragging Event Handlers


<P>Your goal is to drag one noun and one adjective from the following table into the blanks of the sentence. Select a word from the table and drag it to the desired blank. When you release the mouse, the word will appear in the blank. You have two seconds to complete each blank.</P>

NounsAdjectives
truckround
dollred
ballpretty

<P ID="myP" onDragEnter="cancelDefault()" onDragOver="cancelDefault()"

onDrop="handleDrop()">

Pat said, "Oh my, the       is so      !"</P> <BUTTON onClick="location.reload()">Reset</BUTTON> </BODY> </HTML>


 </source>
   
  


Using onDragEnter and onDragLeave Event Handlers

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>onDragEnter and onDragLeave Event Handlers</TITLE> <SCRIPT LANGUAGE="JavaScript"> function showEnter() {

   status = "Entered at: " + new Date()
   event.returnValue = false

} function clearMsg() {

   status = ""
   event.returnValue = false

} </SCRIPT> </HEAD> <BODY>

onDragEnter and onDragLeave Event Handlers


<P>Select any character(s) from this paragraph, and slowly drag it around the page. When the dragging action enters the large header above, the status bar displays when the onDragEnter event handler fires. When you leave the header, the message is cleared via the onDragLeave event handler.</P> </BODY> </HTML>


 </source>
   
  


Using onMouseDown and onMouseUp Event Handlers

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>onMouseDown and onMouseUp Event Handlers</TITLE> <SCRIPT LANGUAGE="JavaScript"> if (document.images) {

   var RightNormImg = new Image(16,16)
   var RightUpImg = new Image(16,16)
   var RightDownImg = new Image(16,16)
   var LeftNormImg = new Image(16,16)
   var LeftUpImg = new Image(16,16)
   var LeftDownImg = new Image(16,16)
   RightNormImg.src = "http://www.wbex.ru/style/logo.png"
   RightUpImg.src = "http://www.wbex.ru/style/logoRed.png"
   RightDownImg.src = "http://www.wbex.ru/style/logo.png"
   LeftNormImg.src = "http://www.wbex.ru/style/logo.png"
   LeftUpImg.src = "http://www.wbex.ru/style/logo.png"
   LeftDownImg.src = "http://www.wbex.ru/style/logoRed.png"

} function setImage(imgName, type) {

   if (document.images) {
       var imgFile = eval(imgName + type + "Img.src")
       document.images[imgName].src = imgFile
       return false
   }

} </SCRIPT> </HEAD> <BODY>

onMouseDown and onMouseUp Event Handlers


<P>Roll atop and click on the buttons to see how the link event handlers swap

images:</P>

<A HREF="javascript:void(0)"

   onMouseOver="return setImage("Left","Up")"
   onMouseDown="return setImage("Left","Down")"

onMouseUp="return setImage("Left","Up")"

   onMouseOut="return setImage("Left","Norm")"

> <IMG NAME="Left" SRC="LeftNorm.gif" HEIGHT=16 WIDTH=16 BORDER=0></A>    <A HREF="javascript:void(0)"

   onMouseOver="return setImage("Right","Up")"
   onMouseDown="return setImage("Right","Down")"
   onMouseUp="return setImage("Right","Up")"
   onMouseOut="return setImage("Right","Norm")"

> <IMG NAME="Right" SRC="RightNorm.gif" HEIGHT=16 WIDTH=16 BORDER=0></A>

</BODY> </HTML>


 </source>
   
  


Using the toElement and fromElement Properties

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman Publisher: John Wiley & Sons CopyRight 2001 ISBN: 0764533428

  • /

<HTML> <HEAD> <TITLE>fromElement and toElement Properties</TITLE> <STYLE TYPE="text/CSS"> .direction {background-color:#00FFFF; width:100; height:50; text-align:center}

  1. main {background-color:#FF6666; text-align:center}

</STYLE> <SCRIPT LANGUAGE="JavaScript"> function showArrival() {

   var direction = (event.fromElement.innerText) ? event.fromElement.innerText :
   "parts unknown"
   status = "Arrived from: " + direction

} function showDeparture() {

   var direction = (event.toElement.innerText) ? event.toElement.innerText :
   "parts unknown"
   status = "Departed to: " + direction

} </SCRIPT> </HEAD> <BODY>

fromElement and toElement Properties


<P>Roll the mouse to the center box and look for arrival information in the status bar. Roll the mouse away from the center box and look for departure information in the status bar.</P>

North
West Roll East
South

</BODY> </HTML>


 </source>
   
  


Which element was clicked

   <source lang="html4strict">
 

<html> <head> <script type="text/javascript"> function whichElement(event){

   var tname
   tname=event.srcElement.tagName
   alert("You clicked on a " + tname + " element.")

} </script> </head> <body onmousedown="whichElement(event)"> <p>Click in the document. </p>

This is a header

<p>This is a paragraph</p> <img border="0" src="http://www.wbex.ru/style/logo.htm"

   width="50" height="50" alt="Ball">

</body> </html>



 </source>
   
  


Which mouse button was clicked?

   <source lang="html4strict">
 

<html> <head> <script type="text/javascript"> function whichButton(event){

   if (event.button==1){
       alert("You clicked the left mouse button!")
   }else{
       alert("You clicked the right mouse button!")
   }

} </script> </head> <body onmousedown="whichButton(event)"> <p>Click in the document. </p> </body> </html>



</source>