CSE 154

Lecture 11: More on events

Announcement & Reminders

First exploration session Thursday 5:30-6:20, MGH 241

Let's Chat Sounding Board! event Friday 4pm

Special requests for exam seating (closes 4/23)

HW3 due today

read the syllabus

Follow up notes

Semantic tags vs "Tags with Semantic Meaning"

Selectors used in querySelector or querySelectorAll do not have to be listed in your .css file

All of the selectors listed in the .html "exist" in the namespace of the page as it is rendered. The styles you define in your .css file overrride the default styles for every selector.

You experienced .classList.remove("hidden") in lab. Today we'll explain more about it (demo)

Clock example (thanks Jeremy!)

But first, quickly finishing lecture 10...

Trying to add two or more event handlers

Using assigment (what we've used so far)


					let button = document.getElementById("mybutton");
					// handleButton initially gets set as the onclick handler
					button.onclick = handleButton;
					// This handleButton2 overrides the handleButton click handler
					button.onclick = handleButton2;
					

JS (example)

If you assign onclick twice, the second assignment replaces the first.

Solution! Use addEventListener

addEventListener allows multiple listeners to be called for the same event


					element.addEventListener("event", function);
					

JS (template)


					let button = document.getElementById("mybutton");
					button.addEventListener("click", func1); // button.onclick = func1
					button.addEventListener("click", func2); // button.onclick = func2
					

JS (example)

Both will now work.

Note that you do not include "on" in the event name!

Multiple window.onload Listeners


					window.onload = function;
					window.addListener("load", function);
					

JS

It is generally considered bad form to directly assign to window.onload (though it is ok for this class)

Multiple .js files could be linked to the same page, and if they all need to run code when the page loads, their window.onload statements will override each other

By calling window.addEventListener instead, all of them can run their code when the page is loaded

More JavaScript Events

JavaScript Events

abort blur change click dblclick error focus
keydown keypress keyup load mousedown mousemove mouseout
mouseover mouseup reset resize select submit unload

The click event (onclick) is just one of many events that can be handled

The Event Object


          function name (event) {
            // an event handler function...
          }
          

JS (template)J

Event handlers can accept an optional parameter to represent the event that is occurring

Event objects have the following properties/methods:

Property Description
type what kind of event, such as "click" or "mousedown"
target the element on which the event occurred
timestamp when the event occurred

Mouse Events

Clicking

Name Description
click user presses/releases mouse button on the element
dblclick user presses/releases mouse button twice on the element
mousedown user presses down mouse button on the element
mouseup user releases mouse button on the element

Movement

Name Description
mouseover mouse cursor enters the element's box
mouseout mouse cursor exits the element's box
mousemove mouse cursor moves around within the element's box

Mouse Events

Property/Method Description
clientX
clientY
coordinates in browser window
screenX
screenY
coordinates in screen
offsetX
offsetY
coordinates in element (non-standard)
button integer representing which button was pressed (0=Left
1=Middle, 2=Right)
mouse event

Mouse Event Example


          Move the mouse over me!
          

HTML


          window.onload = function() {
            let target = document.getElementById("target");
            document.getElementById("target").addEventListener("mousemove", showCoords);
          };

          function showCoords(event) {
            document.getElementById("targetoutput").innerHTML =
               "screen : (" + event.screenX + ", " + event.screenY + ")\n"
            +  "client : (" + event.clientX + ", " + event.clientY + ")\n";
          }
          

JS

screen : (333, 782)
client : (222, 460)
button : 0

output

Keyboard/Text Events

Name Description
focus this element gains keyboard focus (attention of user's keyboard)
blur this element loses keyboard focus
keydown user presses a key while this element has keyboard focus
keyup user releases a key while this element has keyboard focus
keypress user presses and releases a key while this element has keyboard focus
select this element's text is selected or deselected

Key Event Objects

Property Name Description
keyCode ASCII integer value of key that was pressed (convert to char with String.fromCharCode)
altKey, ctrlKey, shiftKey true if Alt/Ctrl/Shift key is being held

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, document, an outer element, etc.

Key Event Example


document.getElementById("textbox").onkeydown = textKeyDown;
...
function textKeyDown(event) {
  let key = String.fromCharCode(event.keyCode);
	document.getElementById("textboxoutput").innerHTML =
		 "key : " + event.keyCode + "\n" +
	+  "altKey : " + event.altKey + "\n" +
	+  "ctrlKey : " + event.altKey;
  }
}
          
key :
altKey :
ctrlKey : 

output

Each time you push down any key, even a modifier such as Alt or Ctrl, the keydown event fires

If you hold down the key, the keydown event fires repeatedly

keypress event is a bit flakier and inconsistent across browsers

Some Useful Keycodes

Keyboard Key Event Keycode
Backspace 8
Tab 9
Enter 13
Escape 27
Page Up, Page Down, End, Home 33, 34, 35, 36
Left, Up, Right, Down 37, 38, 39, 40
Insert, Delete 45, 46
Window/Command 91
F1-F12 112-123

Page/Window Events

Name Description
contextmenu the user right-clicks to pop up a context menu
error an error occurs when loading a document or an image
load the browser loads the page
resize the browser window is resized
scroll the user scrolls the viewable part of the page up/down/left/right
unload the browser exits/leaves the page

The above can be handled on the window object

Stopping an Event

Event Method Description
preventDefault stops the browser from doing its normal action on an event; for
example, stops the browser from following a link when <a> tag
is clicked
stopPropagation stops the browser from showing this event to any other objects that may be listening to it

You can also return false; from your event handler to stop an event

Stopping an Event, example


          
...

HTML


          window.onload = function() {
            let form = document.getElementById("exampleform");
            form.onsubmit = checkData;
          };

          function checkData(event) {
            if (document.getElement("state").length != 2) {
              alert("Error, invalid city/state."); // show error message
              event.preventDefault();
              return false; // stop form submission
            }
          }
          

JS

Event Handler Binding


					window.onload = function() {
						document.getElementById("textbox").onmouseout = booyah;
					};

					function booyah() { // booyah knows what object it was called on
						this.value = "booyah";
					}
					

JS

output

Event handlers attached unobtrusively are bound to the element

Inside the handler, that element becomes this