1 / 17

Javascript Prototype

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.

keegan
Télécharger la présentation

Javascript Prototype

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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/

  2. 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

  3. 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:

  4. 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;

  5. 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

  6. Mouse event objects • The event passed to a mouse handler has these properties/methods: • *   replaces non-standard properties pageXand pageY

  7. 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

  8. 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

  9. Keyboard/text events focus: the attention of the user's keyboard (given to one element at a time)

  10. 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.

  11. 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>

  12. 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>

  13. Prototype dom:loaded event • An alternative to window.onload: window.onload = function() { ... }; document.observe("dom:loaded", function() { // attach event handlers, etc. });

  14. 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(); } }

  15. 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>

  16. 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(); } }

  17. 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(); } }

More Related