210 likes | 496 Views
Javascript Prototype. Chapter 11 JavaScript Tutorial at http://www.w3schools.com/js/ DOM Tutorial at http://www.w3schools.com/htmldom/dom_intro.asp Prototype tutorial at http://prototypejs.org / Or http://api.prototypejs.org/. Attaching event handlers the Prototype way.
E N D
Javascript Prototype Chapter 11 JavaScript Tutorial at http://www.w3schools.com/js/ DOM Tutorial at http://www.w3schools.com/htmldom/dom_intro.asp Prototype tutorial at http://prototypejs.org/ Or http://api.prototypejs.org/
Attaching event handlers the Prototype way • Prototype includes many event-related features and fixes element.onevent = function; element.observe("event", function); // call the playNewGame function when the Play button is clicked $("play").observe("click", playNewGame); • to use Prototype's event features, you must attach the handler using the DOM element object's observemethod (added by Prototype) • pass the event nameas a string, and the function name to call • handlers must be attached this way for Prototype's event features to work
The Event object function name(event) { // an event handler function ... } • When an event handler is called, it is passed a parameter representing the event that occurred. • Event handlers can accept an optional parameter to represent the event that is occurring. • Event objects have the following properties methods:
Mouse events // where element is a DOM element object //function is the event handler element.onevent = function; • clicking • movement Attaching onclick handler to element elementn.onclick = clickMeFunc;
Mouse events: example <p id="counter">99 bottles</p> var count = 99; window.onload = function() { $("counter").observe("mouseover", countBottles); }; function countBottles() { $("counter").innerHTML = (--count) + " bottles"; } 99 bottles After the mouse enters the element, 98 bottles
Mouse event objects • The event passed to a mouse handler has these properties/methods: • * replaces non-standard properties pageXand pageY
Mouse event example • … • <script src="prototype.js" type="text/javascript"></script> • <script src="mouseeventexample.js" type="text/javascript"></script> • </head> • <body> • <pre id="target">Move the mouse over me!</pre> window.onload = function() { $("target").observe("mousemove", showCoords); }; function showCoords(event) { $("target").innerHTML = "event: " + event.type+ "<br/>" +"pointer: (" + event.pointerX() + ", " + event.pointerY()+ ")<br/>" + "screen : (" + event.screenX+ ", " + event.screenY + ")<br/>" + "client : (" + event.clientX+ ", " + event.clientY+ ")"; } mouseeventexample.js
Form event & Stopping an event • <form id="exampleform" action="http://foo.com/foo.php">...</form> window.onload = function() { $("exampleform").observe("submit", checkData); }; function checkData(event) { if ($F("city") == "" || $F("state").length != 2) { alert("Error, invalid city/state."); // show error message event.stop(); return false; } } • to abort a form submit or other event, call Prototype's stop method on the event
Keyboard/text events focus: the attention of the user's keyboard (given to one element at a time)
Keyboard/text events Prototype's key code constants • issue: if the event you attach your listener to doesn't have the focus, you won't hear the event • possible solution: attach key listener to entire page body, outer element, etc.
Example vari = 0; window.onload= function() { $("target").onkeydown= eventStatus; }; function eventStatus(e){ vars = ""; s += "keyCode=" + e.keyCode + "<br/>"; s += "altKey=" + e.altKey + ", ctrlKey=" + e.ctrlKey+", shiftKey=" + e.shiftKey + "<br/><br/>"; s += i++; $("temp").innerHTML = s; } <div> <input id="target" type="text" /> </div> <div id="temp"> </div>
Same Example using observe vari = 0; window.onload= function() { $("target").observe("keydown", function(e) {eventStatus(e, "temp");}); }; function eventStatus(e, id) { vars = ""; s += "keyCode=" + e.keyCode + "<br/>"; s += "altKey=" + e.altKey + ", ctrlKey=" + e.ctrlKey+", shiftKey=" + e.shiftKey + "<br/><br/>"; s += i++; $("temp").innerHTML = s; } <div> <input id="target" type="text" /> </div> <div id="temp"> </div>
Prototype dom:loaded event • An alternative to window.onload: window.onload = function() { ... }; document.observe("dom:loaded", function() { // attach event handlers, etc. });
Data invalidation • ZIP code: <input id="zip" type="text" size="5" maxlength="5" /> document.observe("dom:loaded", function() { $("zip").observe("keydown", zipKeyDown);}); varALLOWED = [Event.KEY_BACKSPACE, Event.KEY_LEFT, Event.KEY_RIGHT]; // Called when a key is pressed on the zip code field. // Disallows non-numeric characters from being typed. function zipKeyDown(event) { varzero = "0".charCodeAt(0); varnine = "9".charCodeAt(0); if ((event.keyCode < zero || event.keyCode> nine) && ALLOWED.indexOf(event.keyCode) < 0) { event.stop(); } }
Multiplication Quiz Example body, input { font-family: "Calibri", "Verdana", "Arial", sans-serif;} #main { margin-left: auto; margin-right: auto; overflow: hidden; width: 40em;} fieldset{ float: left; margin-left: 1em; width: 10em;} fieldset, h1, p { text-align: center;} <h1>Multiplication Quiz</h1> <div id="main"> <fieldset> <legend>Time</legend> <div><span id="time">5</span> sec</div> </fieldset> <fieldset> <legend>Current Problem</legend> <div> <span id="num1"></span> * <span id="num2"></span> = <input id="guess" type="text" size="3" maxlength="3" /> </div> </fieldset> <fieldset> <legend>Score</legend> <div> <span id="correct">0</span> / <span id="total">0</span> </div> </fieldset> </div> <p>You have 5 seconds for each problem. How many can you solve?</p>
Multiplication Quiz Example var MAX_TIME = 5; // 5 seconds for each question var timer = null; // holds ID of timer document.observe("dom:loaded", function() { $("guess").observe("keydown", guessKeyDown); nextProblem(); }); // Chooses two new random numbers for the next quiz problem. function nextProblem() { $("num1").innerHTML = parseInt(Math.random() * 20) + 1; $("num2").innerHTML = parseInt(Math.random() * 20) + 1; $("guess").clear(); $("time").innerHTML = MAX_TIME; clearInterval(timer); timer = setInterval(tick, 1000); } // Called by timer when time has elapsed (user ran out of time) function tick() { var seconds = parseInt($("time").innerHTML); seconds--; $("time").innerHTML = seconds; if (seconds <= 0) { // time up! $("total").innerHTML = parseInt($("total").innerHTML) + 1; nextProblem(); } }
Multiplication Quiz Example // Called when a key is typed in the text box. // On an Enter keypress, checks whether player's guess is correct. function guessKeyDown(event) { numbersOnly(event); if (event.keyCode == Event.KEY_RETURN) { var guess = $F("guess"); var answer = $("num1").innerHTML * $("num2").innerHTML; if (guess == answer) { $("correct").innerHTML = parseInt($("correct").innerHTML) + 1; } $("total").innerHTML = parseInt($("total").innerHTML) + 1; nextProblem(); } } // copied from zip code example function numbersOnly(event) { var ALLOWED = [Event.KEY_RETURN, Event.KEY_BACKSPACE, Event.KEY_LEFT, Event.KEY_RIGHT, Event.KEY_HOME, Event.KEY_END, Event.KEY_TAB]; var zero = "0".charCodeAt(0); var nine = "9".charCodeAt(0); if ((event.keyCode < zero || event.keyCode > nine) && ALLOWED.indexOf(event.keyCode) < 0) { event.stop(); } }