CSE 154 LECTURE 10: MORE EVENTS. Problems with reading/changing styles Click Me HTML window.onload = function() { document.getElementById("clickme").onclick.

Slides:



Advertisements
Similar presentations
Computer Basics Hit List of Items to Talk About ● What and when to use left, right, middle, double and triple click? What and when to use left, right,
Advertisements

The DOM tree CS The DOM tree CS380 2 Types of DOM nodes  element nodes (HTML tag)  can have children and/or attributes  text nodes (text in.
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
CS7026 jQuery Events. What are Events?  jQuery is tailor-made to respond to events in an HTML page.  Events are actions that can be detected by your.
Chapter 6 © 2012 by Addison Wesley Longman, Inc Introduction Def: A dynamic HTML document is one whose tag attributes, tag contents, or element.
Event Handling. Overview How to listen (and not listen) for events Creating a utility library (and why you should) Typology of events Pairing event listeners.
The Web Warrior Guide to Web Design Technologies
Computer Science 103 Chapter 4 Advanced JavaScript.
Cos 381 Day 7. © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Agenda Assignment 2 Posted –Program a web-based Version of Soduku using JavaScript.
Lesson 2 Event Handling. Object Event Handlers Most of the objects that make up the Document Object Model respond to asynchronous, user generated events.
XP Tutorial 8 New Perspectives on JavaScript, Comprehensive1 Working with the Event Model Creating a Drag-and-Drop Shopping Cart.
JavaScript Client Side scripting. Client-side Scripts Client-side scripts, which run on the user’s workstation can be used to: Validate user inputs entered.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
CP476 Internet Computing JavaScript and HTML1 1.JavaScript Execution Environment The JavaScript Window object represents the window in which the browser.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Unobtrusive JavaScript
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
JavaScript Part 1.
The DOM tree CS The DOM tree CS380 2 Types of DOM nodes  element nodes (HTML tag)  can have children and/or attributes  text nodes (text in.
More Events and Validation CS Page/window events CS380 2.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
CO1552 Web Application Development HTML Forms, Events and an introduction to JavaScript.
Client-Side Scripting JavaScript.  produced by Netscape for use within HTML Web pages.  built into all the major modern browsers. properties  lightweight,
CSE 154 LECTURE 18: THE DOCUMENT OBJECT MODEL (DOM); UNOBTRUSIVE JAVASCRIPT.
DOM Events. JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default.
CSE 154 Lecture 20: The DoM tree.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
Events DOM Event Model. HTML Events "on" + event name attribute value is javascript javascript runs 1st return false to STOP browser event (if any)
Event JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. When the page loads, that is.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
JavaScript, Fourth Edition Chapter 4 Manipulating the Browser Object Model.
Thursday, August 6 th, 2015 Instructor: Craig Duckett Event Handling.
DOM Events. JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default.
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Event Handling. Objectives Using event handlers Simulating events Using event-related methods.
Project 8: Reacting to Events Essentials for Design JavaScript Level One Michael Brooks.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 7 TH EDITION Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
7. JavaScript Events. 2 Motto: Do you think I can listen all day to such stuff? –Lewis Carroll.
Event Handling & AJAX IT210 Web Systems. Question How do we enable users to dynamically interact with a website? Answer: Use mouse and keyboard to trigger.
Chapter 6 © 2014 by Pearson Education Introduction Def: A dynamic HTML document is one whose tag attributes, tag contents, or element style properties.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Events CS The keyword this  all JavaScript code actually runs inside of an object  by default, code runs inside the global window object  all.
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
LESSON : EVENTS AND FORM VALIDATION -JAVASCRIPT. EVENTS CLICK.
 objects in Client  What is Event?  Event Handlers  programming.
This is our seminar JavaScript And DOM This is our seminar JavaScript And DOM.
Chapter 6 Dynamic Documents with JavaScript. © 2006 Pearson Addison-Wesley. All rights reserved Introduction Def: A dynamic HTML document is.
CSE 154 LECTURE 9: THE DOM TREE. The DOM tree The elements of a page are nested into a tree-like structure of objects the DOM has properties and methods.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
Internet & World Wide Web How to Program, 5/e.  JavaScript events  allow scripts to respond to user interactions and modify the page accordingly  Events.
Chapter 6 © 2003 by Addison-Wesley, Inc Introduction - Dynamic HTML is not a new markup language - A dynamic HTML document is one whose tag attributes,
6.1 Introduction 6.2 Element Positioning
Introduction to JavaScript Events
CSE 154 Lecture 11: More Events.
Working with the Event Model
Events.
DREAMWEAVER MX 2004 Chapter 3 Working with Tables
Lecture 11: Keyboard Events
CSE 337 Lecture 10: Events.
JavaScript and Events CS Programming Languages for Web Applications
CSE 337 Lecture 10: Events.
CSc 337 Lecture 9: The DoM tree.
CS7026 jQuery Events.
Lecture 11: Keyboard Events
CHAPTER 6 EVENTS. CHAPTER 6 EVENTS WHAT IS AN EVENT?
JavaScript Event Handling For Interaction and Casual Games
Web Programming and Design
6.1 Introduction 6.2 Positioning Elements
JavaScript and Events CS Programming Languages for Web Applications
Presentation transcript:

CSE 154 LECTURE 10: MORE EVENTS

Problems with reading/changing styles Click Me HTML window.onload = function() { document.getElementById("clickme").onclick = biggerFont; }; function biggerFont() { var button = document.getElementById("clickme"); var size = parseInt(button.style.fontSize); button.style.fontSize = (size + 4) + "pt"; } JS style property lets you set any CSS style for an element problem: you cannot read existing styles with it (you can read ones you set using the DOM.style, but not ones that are set in the CSS file ) output

Accessing elements' existing styles window.getComputedStyle(element).propertyName JS function biggerFont() { // turn text yellow and make it bigger var clickMe = document.getElementById("clickme"); var size = parseInt(window.getComputedStyle(clickMe).fontSize); clickMe.style.fontSize = (size + 4) + "pt"; } JS getComputedStyle method of global window object accesses existing styles output

Common bug: incorrect usage of existing styles the following example computes e.g. "200px" "px", which would evaluate to "200px100px" var main = document.getElementById("main"); main.style.top = window.getComputedStyle(main).top "px“; // bad! JS a corrected version: main.style.top = parseInt(window.getComputedStyle(main).top) "px"; // correct JS

Removing a node from the page function slideClick() { var bullet = document.getElementById("removeme"); bullet.parentNode.removeChild(bullet); } JS odd idiom: obj.parentNode.remove(obj);

The keyword this this.fieldName // access field this.fieldName = value; // modify field this.methodName(parameters); // call method JS all JavaScript code actually runs inside of an object by default, code runs in the global window object (so this === window ) all global variables and functions you declare become part of window the this keyword refers to the current object

Event handler binding window.onload = function() { document.getElementById("textbox").onmouseout = booyah; document.getElementById("submit").onclick = booyah; // bound to submit button here }; function booyah() { // booyah knows what object it was called on this.value = "booyah"; } JS event handlers attached unobtrusively are bound to the element inside the handler, that element becomes this output

Fixing redundant code with this Huey Dewey Louie HTML function processDucks() { if (document.getElementById("huey").checked) { alert("Huey is checked!"); } else if (document.getElementById("dewey").checked) { alert("Dewey is checked!"); } else { alert("Louie is checked!"); } alert(this.value + " is checked!"); } JS output if the same function is assigned to multiple elements, each gets its own bound copy

JavaScript events abortblurchangeclickdblclickerrorfocus keydownkeypresskeyuploadmousedownmousemovemouseout mouseovermouseupresetresizeselectsubmitunload 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 Event handlers can accept an optional parameter to represent the event that is occurring. Event objects have the following properties / methods: property namedescription typewhat kind of event, such as "click" or "mousedown" targetthe element on which the event occurred timeStampwhen the event occurred

Mouse events clickuser presses/releases mouse button on the element dblclickuser presses/releases mouse button twice on the element mousedownuser presses down mouse button on the element mouseupuser releases mouse button on the element clicking mouseovermouse cursor enters the element's box mouseoutmouse cursor exits the element's box mousemovemouse cursor moves around within the element's box movement

Mouse event objects The event passed to a mouse handler has these properties: property/methoddescription clientX clientY coordinates in browser window screenX screenY coordinates in screen offsetX offsetY coordinates in element (non-standard) buttoninteger representing which button was pressed (0=Left, 1=Middle, 2=Right)

Mouse event example Move the mouse over me! HTML window.onload = function() { var target = document.getElementById("target"); target.onmousemove = target.onmousedown = showCoords; }; function showCoords(event) { document.getElementById("target").innerHTML = + "screen : (" + event.screenX + ", " + event.screenY + ")\n" + "client : (" + event.clientX + ", " + event.clientY + ")\n" + "button : " + event.button; } JS screen : (333, 782) client : (222, 460) button : 0 output

Keyboard/text events namedescription focusthis element gains keyboard focus (attention of user's keyboard) blurthis element loses keyboard focus keydownuser presses a key while this element has keyboard focus keyupuser releases a key while this element has keyboard focus keypressuser presses and releases a key while this element has keyboard focus selectthis element's text is selected or deselected

Key event objects property namedescription keyCodeASCII integer value of key that was pressed (convert to char with String.fromCharCode)String.fromCharCode altKey, ctrlKey, shiftKeytrue 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) { var key = String.fromCharCode(event.keyCode); if (key == 's' && event.altKey) { alert("Save the document!"); this.value = this.value.split("").join("-"); } } JS 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 key codes keyboard keyevent keyCode Backspace8 Tab9 Enter13 Escape27 Page Up, Page Down, End, Home33, 34, 35, 36 Left, Up, Right, Down37, 38, 39, 40 Insert, Delete45, 46 Windows/Command91 F1 - F

Page/window events namedescription contextmenuthe user right-clicks to pop up a context menu erroran error occurs when loading a document or an image loadload, unloadunloadthe browser loads the page resizethe browser window is resized scrollthe user scrolls the viewable part of the page up/down/left/right unloadthe browser exits/leaves the page The above can be handled on the window object

Multiple listeners to the same event element.addEventListener("event", function); JS var button = document.getElementById("mybutton"); button.addEventListener("click", func1); // button.onclick = func1; button.addEventListener("click", func2); // button.onclick = func2; JS if you assign onclick twice, the second one replaces the first addEventListener allows multiple listeners to be called for the same event addEventListener (note that you do not include "on" in the event name!)

Multiple window.onload listeners window.onload = function; window.addEventListener("load", function); JS it is considered bad form to directly assign to window.onload 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

Form events event namedescription submitform is being submitted resetform is being reset changethe text or state of a form control has changed

Stopping an event event method namedescription preventDefaultstops the browser from doing its normal action on an event; for example, stops the browser from following a link when tag is clicked, or stops browser from submitting a form when submit button is clicked stopPropagationstops the browser from showing this event to any other objects that may be listening for it you can also return false; from your event handler to stop an event

Stopping an event, example... window.onload = function() { var form = document.getElementById("exampleform"); form.onsubmit = checkData; }; function checkData(event) { if (document.getElementById("state").length != 2) { alert("Error, invalid city/state."); // show error message event.preventDefault(); return false; // stop form submission } } JS