WEBPROG MIDTERM Lecture 3 EVENT HANDLERS AND LISTENERS
WEBPROG MIDTERM Lecture 3
EVENT HANDLERS AND LISTENERS
On-event Handlers • On-event handlers are attributes that force an element to "listen" for a specific event to occur. • We might, for instance, listen for a user to click on a specific div element, listen for a form submission, or listen for the user to pass his or her mouse over any input element of a given class.
HTML On-event Handlers On-event Handler onblur onchange onclick ondblclick onfocus onkeydown onkeypress Description The element lost the focus. The element value was changed. A pointer button was clicked. A pointer button was doubleclicked. The element received the focus. A key was pressed down. A key was pressed and released.
HTML On-event Handlers p 2 On-event Handler onkeyup onload onmousedown onmousemove onmouseout Description A key was released. The document has been loaded. A pointer button was pressed down. A pointer was moved within the element. A pointer was moved off of the element.
HTML On-event Handlers p 3 On-event Handler onmouseover onmouseup onreset onselect onsubmit Description A pointer was moved onto the element. A pointer button was released over the element. The form was reset. Some text was selected. The form was submitted.
The get. Element. By. Id() Method • A very common way to reference HTML elements is by their id using the get. Element. By. Id() method of the document object. • Once we have the element - that is, once we get a given div, p, input or other DOM element via the get. Element. By. Id() method - we can then listen for events on that element.
Code Sample get-element-by-id. html <!DOCTYPE html> <head> <script> function change. Bg(id, color) { document. get. Element. By. Id(id). style. background. Color = color; } </script> <title>get. Element. By. Id()</title> </head> <body> <main> <button onclick="change. Bg('div. Red', 'red')">R ed </button> <button onclick="change. Bg('div. Orange', 'oran ge')">Orange</button> <button onclick="change. Bg('div. Green', 'green ')">Green</button> <button onclick="change. Bg('div. Blue', 'blue')" >Blue</button> <div id="div. Red">Red</div> <div id="div. Orange">Orange</div> <div id="div. Green">Green</div> <div id="div. Blue">Blue</div> </main> </body> </html>
Activity 4 Using On-event Handlers 1. Create a file named activity 4_colorchanger. html. 2. From the Code Sample get-element-byid. html, modify the page so that… a) When the "Red" button is clicked, the background color turns red. b) When the "Green" button is double-clicked, the background color turns green.
Activity 4 p 2 c) When the "Orange" button is clicked down, the background color turns orange and when the button is released (onmouseup), the background color turns white. d) When the mouse hovers over the "pink" link, the background color turns pink. When it hovers off, the background color turns white. • Add functionality so that when the user presses any key, the background color turns white.
The add. Event. Listener() Method • An Event. Listener represents an object that does something when an event occurs. • Think of a swimmer on a block, waiting for the starting gun to go off. When the gun goes off, the swimmer dives. Here is some pseudo-code to set that up in Java. Script: diver. add. Event. Listener('shot. Fire', dive); • In the pseudo-code above, diver is the Event. Target, shot. Fire is the event type, and dive is the function that will be called when the event occurs. Functions that are called in response to an event are known as callback functions. • An Event. Target is any object on which an event can occur, including window, document, and any HTML element.
Syntax • object. add. Event. Listener(event. Type, callback. Function); • We have already seen the different types of events: click, dblclick, load, mouseover, mouseout, etc. HTML attributes used to call these events all begin with "on", but when referencing the event type directly, you do not include the "on" prefix. • For example, the code on the next slide shows how to call the init() function when the load event of the window object occurs:
Code Sample: window-load. html <!DOCTYPE html> <head> <script> function init(e) { alert('Hello, world!'); } window. add. Event. Listener ('load', init); </script> <title>window load</title> </head> <body> <main> <p>Nothing to show here. </p> </main> </body> </html>
Code Explanation • Notice in the code that init is passed to add. Event. Listener() without the usual trailing parentheses associated with functions. It is window. add. Event. Listener('load', init); and not window. add. Event. Listener('load', init() ); The reason is that we are not calling the function at this point in the code. Rather, we are indicating that we want the function to be called when the relevant event occurs. If you make the mistake of including the parentheses, the function will be called immediately and the value returned from the function will be used as the callback function, probably resulting in an error.
Event Types Event Type blur change click dblclick focus keydown keypress Description The element lost the focus. The element value was changed. A pointer button was clicked. A pointer button was double-clicked. The element received the focus. A key was pressed down. A key was pressed and released.
Event Types Event Type keyup load mousedown mousemove mouseout mouseover Description A key was released. The document has been loaded. A pointer button was pressed down. A pointer was moved within the element. A pointer was moved off of the element. A pointer was moved onto the element.
Event Types Event Type mouseup reset select submit Description A pointer button was released over the element. The form was reset. Some text was selected. The form was submitted.
The callback Function • In the previous example the callback function is init(e). You may have noticed that it takes a single parameter, which we have called e, but the variable name is arbitrary. Common names are e and evt. This parameter will hold the event that caused the callback function to be called.
Code Sample window-load-e. html <!DOCTYPE html> <head> <script> function init(e) { alert(e); alert(e. current. Target); alert(e. type); } window. add. Event. Listener ('load', init); </script> <title>window load</title> </head> <body> <main> <p>Nothing to show here. </p> </main> </body> </html>
Code Explanation • This time, instead of alerting "Hello, world!", the code alerts e: [object Event] and then alerts the current. Target property of the event, which is the object that caused the event to occur: [object Window]. Finally, it alerts the type of event: load. • Now let's take a look at how we use this passing of the event to make a function's response dependent on the event that spawned it on the next code example….
Code Sample: current-target. html <!DOCTYPE html> <head> <script> function change. Bg(e) { var color = e. current. Target. id; document. body. style. background. Co lor = color; } function init(e) { var aqua = document. get. Element. By. Id('aqua'); var lime = document. get. Element. By. Id('lime'); var pink = document. get. Element. By. Id('pink'); aqua. add. Event. Listener('click', change. Bg); lime. add. Event. Listener('click', change. Bg); pink. add. Event. Listener('click', change. Bg); } window. add. Event. Listener('load', init); </script> <title>window load</title> </head> <body> <main> <button id="aqua">Aqua</button> <button id="lime">Lime</button> <button id="pink">Pink</button> </main> </body> </html>
Code Explanation • When the page is loaded the init() function is called. It adds event listeners to each of the buttons, all with the same callback function: change. Bg. Note that we have to add these event listeners after the document loads to be sure that the buttons exist. That is why we do it in the callback function of window's load event. • The callback function, change. Bg(), sets the color variable to the value of the id of the event's current. Target - the button that was clicked. It then changes the background color to color.
Anonymous Functions • The init() function in the sample is meant to be called once and only once - when the page finishes loading. As such, there is no reason for it to remain available after it is run. Such functions are often created as anonymous functions at the point in the code that they are needed. The syntax is as follows: Syntax object. add. Event. Listener(event. Type, function(e) { // function code here }); • Notice the function has no name: function init(e) is replaced with function(e). It doesn't need a name, because it will only be referenced this one time in the code.
Code Sample: anonymous-function. html <!DOCTYPE html> <head> <script> function change. Bg(e) { var color = e. current. Target. id; document. body. style. background. Col or = color; } window. add. Event. Listener('load', function(e) { var aqua = document. get. Element. By. Id('aqua'); var lime = document. get. Element. By. Id('lime'); var pink = document. get. Element. By. Id('pink'); aqua. add. Event. Listener('click', change. Bg); lime. add. Event. Listener('click', change. Bg); pink. add. Event. Listener('click', change. Bg); }); </script> <title>Anonymous Function</title> </head> <body> <main> <button id="aqua">Aqua</button> <button id="lime">Lime</button> <button id="pink">Pink</button> </main> </body> </html>
Code Explanation • Note that we could make change. Bg() an anonymous function as well, but because it is called three times, we would have to change it each place it is called. If we ever wanted to change it, we would have to change it in all three places. So, as it is reused, it makes more sense to give that one a name.
Capturing Key Events The three types of keyboard events are: • keydown - fires when a key is pressed down. • keyup - fires when a key is released. • keypress - fires when a key is pressed down and then released. • The target of keyboard events can be the document or any element on the page. • When capturing a keyboard event, it is common to want to know what key is pressed. This is available via the event's key property.
Code Sample: keys. html <!DOCTYPE html> <head> <script> document. add. Event. Listener('keypress', function(e) { document. get. Element. By. Id('keyholder'). inner. HTML = e. key; }); </script> <title>Key Press</title> </head> <body> <main id="keyholder"></main> </body> </html>
Code Explanation • Run this page in your browser and press any key to see how it works. Notice that when you press the Enter key, the word "Enter" is output. You could use the code below to capture this on an input field: var my. Input = document. get. Element. By. Id('my. Input'); my. Input. add. Event. Listener('keypress', function(e) { if (e. key === 'Enter') { do. Something(); } }); • This demo uses the inner. HTML property, which you can use to read and modify the HTML content of an element.
Benefits of Event Listeners • Using on-event handlers such as onclick and onmouseover is simple and straightforward, while using event listeners requires more Java. Script to set things up, so why use event listeners? • There at least two major benefits to using event listeners: 1. You can add multiple event listeners to the same element. 2. Your HTML and Java. Script code are decoupled, which provides for easier maintenance and debugging.
Code Sample benefits. js function color() { document. body. style. background. Col or = 'red'; } function reset() { document. body. style. background. Col or = 'white'; } function log(e) { var t = e. current. Target; console. log(t. id + ' clicked'); } window. add. Event. Listener('load', function() { var btn. Color = document. get. Element. By. Id('btncolor'); btn. Color. add. Event. Listener('click', color); btn. Color. add. Event. Listener('click', log); var btn. Reset = document. get. Element. By. Id('btnreset'); btn. Reset. add. Event. Listener('click', reset); btn. Reset. add. Event. Listener('click', log); });
Code Explanation • Notice that you don't need to see the HTML to understand how • • this code will work and when it will run. The color() and reset() functions just change the background color of the page. The log(e) function logs the button click. Here we just log it to the console, but in practice, we could log it to a permanent location using Ajax, which we do not cover in this course. Each button gets two event listeners: one to change the color and the other to log the event. We couldn't do this with an onclick tag without rewriting our Java. Script to combine the logging with the color-changing functions. To see how it works, open event-listeners-benefits. html in Google Chrome with the console open and click on the buttons several times.
Code Sample event-listenersbenefits. html <!DOCTYPE html> <head> <script src="benefits. js"></script> <title>Event Listeners Benefits</title> </head> <body> <main> <button id="btn-color">Color</button> <button id="btn-reset">Reset</button> </main> </body> </html>
Activity 5 Adding Event Listeners You will start with the code below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1"> <link rel="stylesheet" href=". . /normalize. css"> <link rel="stylesheet" href=". . /styles. css"> <script> // write change. Bg function here function change. Bg. White(e) { document. body. style. background. Color = 'white'; } // add your event listener here </script> <title>Color Changer</title> </head> <body> <main> <button id="red"> Click to turn the page red. </button> <button id="green"> Double-click to turn the page green. </button> <button id="orange"> Click and hold to turn the page orange. </button> <a href="#" id="pink">Hover to turn page pink. </a> </main> </body> </html>
Activity 5 p 2 Add an event listener to capture the load event of the window object. The callback function should be anonymous and should do the following: 1. Create variables holding the buttons and link. 2. Add a click event to the red button that calls change. Bg. 3. Add a dblclick event to the green button that calls change. Bg. 4. Add a mousedown event to the orange button that calls change. Bg. 5. Change the change. Bg. White() function as follows: function change. Bg. White(e) { change. Bg('white'); }
Activity 5 p 3 6. Add a mouseup event to the orange button that calls change. Bg. White. 7. Add a mouseover event to the link that calls change. Bg. 8. Add a mouseout event to the link that calls change. Bg. White. 9. Add a keypress event to the document object that calls change. Bg. White. • Write the change. Bg() function to allow for a color value as a string as well as an event. If an event is passed in, it should get the color from the id of the current. Target of the event. But if a string is passed in, it should use that string as the color value.
Code Explanation • We need a change. Bg. White() function because we cannot key off the id value to change the background color to white for two reasons: We have added two event handlers to the btn. Orange button: mousedown and mouseup. For mouse. Down, we call change. Bg(), which keys off btn. Orange's id attribute ("orange") to change the background color to orange. For mouseup though, we want to change the background color to white, so we cannot call change. Bg() again as that sets the color to the button's id value. That's why we need change. Bg. White(). The same logic applies to the lnk. Pink link. 2. The document object doesn't have an id value, so for keypress events, if we call change. Bg(), the e. current. Target. id value would be null. That's why we call change. Bg. White() instead. 1.
Timers • Timers are started and stopped with the following four methods of the windows object: 1. set. Timeout(function, wait. Time) - wait. Time is in milliseconds. 2. clear. Timeout(timer) 3. set. Interval(function, interval. Time) - interval. Time is in milliseconds. 4. clear. Interval(interval)
Code Sample timer. html <!DOCTYPE html> <head> <script> // Create global timer variable var timer; function change. Bg(e) { var color = e. current. Target. id; timer = set. Timeout(function() { document. body. style. background Color=color; }, 1000); } function stop. Timer() { clear. Timeout(timer); alert('Timer cleared!'); } window. add. Event. Listener('load', function() { btn. Red = document. get. Element. By. Id('red'); btn. White = document. get. Element. By. Id('white'); btn. Stop = document. get. Element. By. Id('stop'); btn. Red. add. Event. Listener('click', change. Bg); btn. White. add. Event. Listener('click', change. Bg); btn. Stop. add. Event. Listener('click', stop. Timer); }); </script> <title>Timer</title> </head> <body> <main> <button id="red">Change Background to Red</button> <button id="white">Change Background to White</button> <button id="stop">Wait! Don't do it!</button> </main> </body> </html>
Code Explanation • Things to notice: 1. We make timer a global variable so that we can access the timer object from within multiple functions. 2. In the change. Bg() function, we create the timer using set. Timeout(). The first argument of set. Timeout() is the function to execute and the second argument is the number of milliseconds to wait before executing it. 3. The stop. Timer() function simply clears the timer using clear. Timeout(). • The set. Interval() and clear. Interval() methods work the same way. The only difference is that the code gets executed repeatedly until the interval is cleared.
Code Sample interval. html <!DOCTYPE html> <head> <script> // Create global interval and color variables var interval; var color = 'white'; function start. Toggling. Bg() { interval = set. Interval(function() { if (color === 'white') { color = 'red'; } else { color = 'white'; } document. body. style. background. Color=c olor; }, 500); } function stop. Toggling. Bg() { clear. Interval(interval); } window. add. Event. Listener('load', function() { btn. Start = document. get. Element. By. Id('start'); btn. Stop = document. get. Element. By. Id('stop'); btn. Start. add. Event. Listener('click', start. Toggling. Bg); btn. Stop. add. Event. Listener('click', stop. Toggling. Bg); }); </script> <title>Timer</title> </head> <body> <main> <button id="start">Start</button> <button id="stop">Stop</button> </main> </body> </html>
Activity 6 Typing Test inner. HTML - This activity uses the inner. HTML property, which you can use to read and modify the HTML content of an element. • Here is the starting code: ---- C O D E O M I T T E D ---<script> // Global variable containing time passed var time. Passed = 0; function check. Sentence(sentence, entry) { var msg = document. get. Element. By. Id('message'); if (sentence === entry) { msg. inner. HTML = 'You finished in ' + time. Passed + ' seconds'; return true; } time. Passed +=. 1; time. Passed = parse. Float(time. Passed. to. Fixed(1)); msg. inner. HTML = time. Passed + ' seconds'; return false; } window. add. Event. Listener('load', function() { var sentence = document. get. Element. By. Id('sentence'). inner. HTM L; var entry. Field = document. get. Element. By. Id('entry'); // Write your code here. }); </script> <title>Typing Test</title> </head> <body id="typing-test"> <main> <div id="container"> <p id="sentence">The quick brown fox jumps over the lazy dog. </p> <input id="entry" placeholder="Click to start timer. "> <p id="message">0 seconds</p> </div> </main> </body> </html>
Activity 6 p 2 • Beneath the line where entry. Field is declared, add an event listener to entry. Field, so that when the user focuses on the field, an interval is created. The interval's function should run every 100 milliseconds and should do the following: • Call check. Sentence(), passing in the sentence and the value of entry. Field and assigning the result to a variable. • If check. Sentence() returns true, clear the interval.
- Slides: 42