DOM and Events Document Object Model (DOM) Events Handling in JavaScript Svetlin Nakov Technical Trainer Software University

Slides:



Advertisements
Similar presentations
The jQuery library. What is jQuery ? A javascript lightweight library Is very easy to use Is powerful Is cross-browser compatible Downloadable from jQuery.com,
Advertisements

JQuery CS 380: Web Programming. What is jQuery? jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling,
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Philly.NET Hands-On jQuery + Plug-ins Bill Wolff, Rob Keiser.
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 JavaScript and HTML Documents.
Lecture 11 – DOM Scripting SFDV3011 – Advanced Web Development Reference: 1.
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
5.2 DOM (Document Object Model). 2 Motto: To write it, it took three months; to conceive it three minutes; to collect the data in it — all my life. —F.
INTRODUCTION TO HTML5 Using jQuery with HTML5. Introducing jQuery  Although it is not a part of any W3C or WHATWG specification, jQuery performs an important.
DOM Events. JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default.
Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Unleash the Power of jQuery Doncho Minkov Telerik Software Academy academy.telerik.com Senior Technical Trainer
DOM Document Object Model (DOM) SoftUni Team Technical Trainers Software University
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
SASS & LESS Syntactically Awesome StyleSheets Dynamic StyleSheet Language Svetlin Nakov Technical Trainer Software University
Unleash the Power of jQuery Learning & Development Team Telerik Software Academy.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Review of the DOM Node properties and methods Some ways of accessing nodes Appending, copying and removing nodes Event handling – Inline – Scripting –
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Web Development Tools Tools for Front-End Developers Writing HTML and CSS Code SoftUni Team Technical Trainers Software University
JQuery Overview Unleash the Power of jQuery SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
Dr. Ahmet Cengizhan Dirican BIL 374 Internet Technologies 5. JavaScript and HTML Documents.
7. JavaScript Events. 2 Motto: Do you think I can listen all day to such stuff? –Lewis Carroll.
School of Computing and Information Systems CS 371 Web Application Programming JavaScript - DOM Modifying the Page from within.
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.
Host Objects: Browsers and the DOM
Bootstrap Front-End Framework for Responsive Web Sites Svetlin Nakov Technical Trainer Software University
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
JavaScript Tools Tools for Writing / Editing / Debugging JavaScript Code Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Jozef Goetz contribution, © by Pearson Education, Inc. All Rights Reserved.
Sets, Dictionaries SoftUni Team Technical Trainers Software University
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.
Introduction to JavaScript DOM Instructor: Sergey Goldman.
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Chapter 5 Host Objects: Browsers.
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
SE-2840 Dr. Mark L. Hornick 1 Dynamic HTML Handling events from DOM objects.
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
THE DOM.
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
CS 371 Web Application Programming
Introduction to JavaScript Events
Document Object Model (DOM): Objects and Collections
JavaScript and HTML Documents
JavaScript and Events CS Programming Languages for Web Applications
Chengyu Sun California State University, Los Angeles
CHAPTER 6 EVENTS. CHAPTER 6 EVENTS WHAT IS AN EVENT?
JavaScript and Events CS Programming Languages for Web Applications
Presentation transcript:

DOM and Events Document Object Model (DOM) Events Handling in JavaScript Svetlin Nakov Technical Trainer Software University

2 1.Document Object Model (DOM)  The DOM API Overview  Selecting DOM Elements  NodeLists (Live & Static) 2.JavaScript Event Model  Registering Event Handlers  The "event" Object  Capturing and Bubbling Events Table of Contents

Document Object Model (DOM)

4  What is Document Object Model (DOM)?  A concept of representing a HTML document as a "DOM tree"  Consists of elements that have child elements  Elements have properties (attribute + value) and events  DOM provides an API for traversing / modifying the DOM tree  Enables developers to modify the HTML content and the visual presentation of the currently loaded HTML document  E.g. load a table data (JSON) and show it as a HTML table Document Object Model

The DOM API

6  Web browsers provide a DOM API  Consists of objects and methods to interact with the HTML page  Can add / modify / remove HTML elements  Can add / modify / remove HTML attributes  Can apply CSS styles dynamically  HTML elements and their properties are mapped to JS objects  document.documentElement is the element  document.body is the element of the page The DOM API

7  All HTML elements have common properties  Corresponding to the their HTML attributes  id, className, style, onclick, etc.  innerHTML  Holds a string – the content of the element, without the element  outerHTML  Holds a string – the content of the element, with the element  innerText / textContent  Holds a string – the text content of the element, without the tags HTML Elements – Common Properties

8  Each HTML element has a corresponding DOM object type  HTMLLIElement represents  HTMLAudioElement represents  Each of these objects have its specific properties  HTMLAnchorElement has href property  HTMLImageElement has src property  HTMLInputElement has value property  The document object is a special object  It represents the entry point for the DOM API (the DOM tree root) DOM Objects and Types

DOM Objects Live Demo

Selecting DOM Elements

 Select a single element  returns HTMLElement  Select a collection of elements  returns a collection  Access the predefined collections of elements Selecting HTML Elements from DOM var header = document.getElementById('header'); var nav = document.querySelector('#main-nav'); var inputs = document.getElementsByTagName('li'); var radiosGroup = document.getElementsByName('genders[]'); var header = document.querySelectorAll('#main-nav li'); var links = document.links; var forms = document.forms; 11

12  Select element by ID  returns HTMLElement  Select elements by CSS class  returns a collection  Select elements tag name  returns a collection  Select element by name (in forms)  returns a collection Selecing with document.getElementsBy… var header = document.getElementById('header'); var posts = document.getElementsByClassName('post-item'); var sidebars = document.getElementsByTagName('sidebar'); var gendersGroup = document.getElementsByName('genders[]');

document.getElementsBy… Live Demo

14  CSS-like selectors for accessing the DOM tree  querySelector(…)  Returns the first element that matches the selector  querySelectorAll(…)  Returns a collection of all elements that match the selector Query Selectors var header = document.querySelector('#header'); var tableCells = document.querySelectorAll('table tr td'); var selectedLi = document.querySelector('menu > li.selected'); var specialLinks = document.querySelectorAll('a.special');

Query Selectors Live Demo

 HTML elements support select for their inner elements  Select all DIVs that are inside an element with id " wrapper "  All methods can be used on HTML elements  Except getElementById() Selecting Inner Elements var wrapper = document.getElementById('wrapper'); var divsInWrapper = wrapper.getElementsByTagName('div'); 16

Selecting Inner Elements Live Demo

NodeList

 A NodeList is a collection returned by the DOM selectors:  getElementsByTagName(tagName)  getElementsByName(name)  getElementsByClassName(className)  querySelectorAll(selector)  NodeList var divs = document.getElementsByTagName('div'); var queryDivs = document.querySelectorAll('div'); for (var i=0; i<divs.length; i++) { // Do something with divs[i] … // Do something with divs[i] …} 23

Live Demo NodeList

Static NodeList & Live NodeList

22  There are two kinds of NodeList collections  getElementsBy…() returns a live NodeList  querySelectorAll() returns a static NodeList  Live lists keep track of the selected elements  Even when changes are made to the DOM  While static list contain the elements as they were at the execution of the method  Keep in mind that live NodeList is slower than a regular array  Need to cache its length for better performance Static and Live NodeList

Static NodeList and Live NodeList Live Demo

Traversing the DOM Create, Remove, Alter and Append HTML Elements body div#wrapper footerheader h1#logo nav #main-nav h2 nav

25  DOM elements know their position in the DOM tree  Parent: element.parentNode  Returns the direct parent of the element (null for the document)  Children: element.childNodes  Returns a NodeList of all the child nodes (including the text nodes)  First / last child – element.firstChild / element.lastChild  Siblings (elements around the element):  element.nextSibling / element.nextElementSibling  element.previousSibling / element.previousElementSibling Traversing the DOM

26 Traversing the DOM – Example var trainersList = document.getElementsByClassName("trainers-list")[0]; document.getElementsByClassName("trainers-list")[0]; var parent = trainersList.parentNode; log("parent of trainers-list: " + parent.nodeName + " with id: " + parent.id); " with id: " + parent.id); var children = trainersList.childNodes; log("elements in trainers-list: " + children.length); log("element in trainers-list"); for (var i = 0, len = children.length; i < len; i++) { var subItem = children[i] var subItem = children[i] log(subItem.nodeName + " content: " + subItem.innerText); log(subItem.nodeName + " content: " + subItem.innerText);}

27  DOM can be manipulated dynamically with JS  HTML elements can be created  HTML elements can be removed  HTML elements can be altered  Change their content  Change their styles  Change their attributes Manipulating the DOM

28  The document object can create new HTML elements  document.createElement(elementName)  Newly created elements are not in the DOM (the web page)  Must be appended to DOM manually Creating HTML Elements var studentsList = document.createElement("ul"); studentsList.innerHTML = "Student: Pesho"; var liElement = document.createElement("li"); studentsList.appendChild(studentLi); document.body.appendChild(studentsList);

 The DOM API supports inserting a element before or after a specific element  element.appendChild(child)  Inserts the element always at the end of the DOM element  parent.insertBefore(newNode, specificElement)  Inserts the element before specific element  parent.insertAfter(newNode, specificElement)  Inserts the element after specific element Inserting Elements Before / After Element

 Elements can be removed from the DOM  Using element.removeChild(elToRemove)  Pass the element-to-remove to their parent Removing Elements var trainers = document.getElementsByTagName("ul")[0]; var trainer = trainers.firstChild; trainers.removeChild(trainer); // Remove a selected element var selectedElement = //select the element selectedElement.parentNode.removeChild(selectedElement);

 DOM elements can be changed and removed  With the DOM API each DOM element node can be altered  Change its properties or appearance Altering the Elements text text … var second = document.getElementById("s"); var theP = document.getElementById("the-p"); second.appendChild(theP);… // The DOM is: text text

 The DOM API supports appending DOM elements to a element  parentNode.appendChild(node)  Appends the DOM element node to the DOM element parentNode  If parentNode is appended to the DOM, the childN ode is also appended Appending DOM Elements

DOM Optimizations

 Appending elements to the DOM is a very slow operation  When an elements is appended to the DOM, the DOM is rendered anew  All newly created elements must be appended together  Here comes the DocumentFragment element  It is a minimal DOM element, with no parent  It is used to store ready-to-append elements and append them at once to the DOM Optimizing the Appending of Elements

 Using DocumentFragment  Append the elements to a DocumentFragment  Appending DocumentFragment to the DOM appends only its child elements  Using DocumentFragment var div = document.createElement('div'); var dFrag = document.createDocumentFragment(); dFrag.appendChild(div);document.body.appendChild(dFrag);

JavaScript Event Model

37  The DOM event model provides notifications for certain events  E.g. execute a JS function when a button is clicked  The DOM event model consists of events and event listeners attached to the DOM objects  Events Demo Events Demo Event Model

38  DOM provides access to many events  Mouse events – mouse clicks, mouse moves, mouse over, …  Touch events – finger touch, touch start, end, move, …  Form events – field focus, value change, form submit, …  Keyboard events – key down, key up, key press, …  DOM / UI events – node insert, node remove, load, resize, …  Full list of all DOM event types:   You may also define custom event types Event Types

39 Common Event Types load abort select resize change click hover mouseup mousedown mouseover mouseout keydown keypress keyup focus blur focusin focusout  Mouse events  DOM / UI events  Keyboard events  Focus events touchstart touchend touchcancel touchleave touchmove  Touch events

Event Handler Registration

41  Event handling JavaScript code can be specified in the HTML attributes onclick, onload, onmouseover, onresize, … Define Event Handler in the HTML Code Click Me! Click Me! function buttonClickFunction() { console.log("You clicked the [Click Me!] button"); console.log("You clicked the [Click Me!] button");} OK OK

42  Event handling JavaScript code can be specified in the JS code through the properties onclick, onresize, … Define Event Handler in the JS Code Click Me! Click Me! Click me Click me var button = document.getElementById("click-button"); button.onclick = function onButtonClick() { console.log("You clicked the button"); console.log("You clicked the button");}

43  A more powerful way for attaching event handlers:  isCaptureEvent : catch the "capture" or "bubbling" phase  Can attach multiple events in a chain Using addEventListener(…) domElement.addEventListener( eventType, eventHandler, isCaptureEvent) eventType, eventHandler, isCaptureEvent) var button = document.getElementById("buttonOK"); button.addEventListener("click", function() { console.log("You clicked me"); console.log("You clicked me"); }, false);

Event Handlers Live Demo

The "event" Object Just take it

46  The " event " object holds information about the event  Passed as parameter to the event handling function  The event object contains information about:  The type of the event (e.g. 'click', 'resize', …)  The target of the event (e.g. the button clicked)  The key pressed for keyboard events  The mouse button / cursor position for mouse events The "event" Object btn.onclick = function(event) { alert(event); }

47 Event Object  The " event " object is the only argument of the event handler  Old IE versions pass the event in window.event function onButtonClick(event) { console.log(event.target); console.log(event.type); console.log("(" + event.clientX + ", " + event.clientY + ")"); } button.addEventListener("click", onButtonClick, false); function onButtonClick(event) { if (!event) event = window.event; if (!event) event = window.event; // Your event handling code … // Your event handling code …}

The "event" Object Live Demo

Capturing and Bubbling Events

50  When the user clicks on an HTML element  E.g. on a button in the page  The event is also fired on all of its parents  The button is still the target  But the click event is fired on all of its parents  The click event is fired on all elements in the chain Browser Events Chain

 Capturing handlers go down the chain  The first executed handler is on the parent  The last executed handler is on the target  Bubbling handlers bubble up to the parent  The first executed handler is on the target  Then its parent's, and its parent's, etc.  Capturing and Bubbling Explained Capturing and Bubbling Explained Event Chains: Types domElement.addEventListener(eventType, eventHandler, isCaptureEvent) eventHandler, isCaptureEvent) 51

Event Chain Live Demo

53 1.Document Object Model (DOM)  The DOM API  Selecting DOM elements  NodeLists (live & static)  Creating / modifying / deleting elements 2.JavaScript Event Model  Event handler registration  The "event" Object  Capturing and bubbling events Summary

? ? ? ? ? ? ? ? ? JavaScript DOM and Events

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 55  Attribution: this work may contain portions from  “JavaScript Basics" course by Telerik Academy under CC-BY-NC-SA licenseJavaScript BasicsCC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg