DOMJavascript Hadassah Academic College Dr Solange Karsenty 1

  • Slides: 34
Download presentation
DOM/Javascript מבוא ל Hadassah Academic College Dr Solange Karsenty 1

DOM/Javascript מבוא ל Hadassah Academic College Dr Solange Karsenty 1

The Document Object Model (DOM) Document Object Model : הדפדפן יוצר מודל הנקרא ,

The Document Object Model (DOM) Document Object Model : הדפדפן יוצר מודל הנקרא , כאשר דף אינטרנט טעון Document Object Model - נתכוון ל DOM בכל מקום בו נרשום , עתה זה מה שקורא הדפדפן <html> <head> <title>Sample DOM Document</title> </head> <body> <h 1>An HTML Document</h 1> <p>This is a <i>simple</i> document. </body> </html> זה מה שמציג הדפדפן על המסך 2

Document The Document Object Model (DOM) Javascript זהו מבנה של עץ זמין ב NODE

Document The Document Object Model (DOM) Javascript זהו מבנה של עץ זמין ב NODE כל קודקוד נקרא <html> <head> <body> <title> "Sample DOM Document" <h 1> <p> "An HTML Document" "This is a" <i> "simple" "document" 3

DOM Structure • Objects are in a hierarchy • The window is the parent

DOM Structure • Objects are in a hierarchy • The window is the parent for a given web page • Document is the child with the objects that are most commonly manipulated window - the browser window • Global objects: Has properties for following objects (e. g. , window. document) Or can refer to them directly (e. g. , document) document - the current web page history - the list of pages the user has visited previously location - URL of current web page navigator - web browser being used screen - the area occupied by the browser & page window * location * history * navigator * event * screen * document o links o anchors o images o filters o forms o applets o embeds o plug-ins o frames o scripts o all o selection o stylesheets o body 6

What is Javascript • A programming language! • Java. Script is a scripting language

What is Javascript • A programming language! • Java. Script is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages. • Java. Script can put dynamic text into an HTML page • A Java. Script statement like this: document. write("<h 1>" + name + "</h 1>") can write a variable text into an HTML page. • Java. Script can react to events • A Java. Script can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element. • Java. Script can read and write HTML elements • A Java. Script can read and change the content of an HTML element. • Java. Script can be used to validate data • A Java. Script can be used to validate form data before it is submitted to a server, this will save the server from extra processing. 7

Event example ● the code: <a href="http: //www. nowhere. com" onclick="alert('I said don't do

Event example ● the code: <a href="http: //www. nowhere. com" onclick="alert('I said don't do that!!!'); return false; "> Don't click here </a> ● onclick is an event. ● ● זהו האירוע שקורה כאשר לוחצים על הקישור alert is a function. ● זאת הפונקציה הבסיסית על מנת להציג הודעה למשתמש 8

Events ( )אירועים • Events: • אירוע נוצר כתוצאה מפעולה של המשתמש או על

Events ( )אירועים • Events: • אירוע נוצר כתוצאה מפעולה של המשתמש או על ידי הדפדפן • Common User actions ( )פעולות נפוצות של המשתמש • on. Mouse. Over, on. Mouse. Out, on. Click • These 3 events are mostly commonly used with anchor tags • Others include on. Focus, on. Blur • Document events ( )אירועים שלא נוצרו ע״י המשתמש • on. Load and on. Un. Load are examples of events not triggered by the user. 9

Alert • alert is used to grab the attention of the user • Syntax:

Alert • alert is used to grab the attention of the user • Syntax: alert(string); • Ex: alert(“You have not entered a valid name. ”) • Ex. alert(“Hello “ + name + “!”); • The look of the alert box is defined by the browser and platform. • Gets the users attention but abusing it can easily be abused • Modern libraries have more advanced dialogs (avoid using this function as is) 10

Working with the URL (location) • Some properties • • • location. href -

Working with the URL (location) • Some properties • • • location. href - full URL of current location. protocol - protocol being used location. host - hostname location. port location. pathname • Can navigate to new page by updating the current location • location. href = ‘[new URL]’; 11

History • history. back(), • history. forward(), • history. go(delta) • takes you back

History • history. back(), • history. forward(), • history. go(delta) • takes you back to (delta) URL in history array • What if you have an SPA & user navigates through different views? • Want to be able to jump between different views within a single URL • Solution: manipulate history state • Add entries to history stack describing past views • Store and retrieve object using history. push. State() and history. state 12

Script example • The code is inserted in the HTML document: <script language="javascript"> <!-var

Script example • The code is inserted in the HTML document: <script language="javascript"> <!-var now = new Date(); var hour = now. get. Hours(); if (hour > 5 && hour <= 11) { document. write("<b>Good Morning!</b>"); } else if (hour > 11 && hour <= 17) { document. write("<b>Good Afternoon!</b>"); } else { document. write("<b>Good Evening!</b>"); } // --> • <script> is the tag used to indicate that you are writing javascript and not html. • if and else are used to make conditional statements. • document. write tells javascript to insert html into the page: it replaces the entire content of the page! Therefore it is not commonly used. Instead we want to modify only some parts of the page. </script> 13

The <script> tag • The main property of <script> is language. • Eg. <script

The <script> tag • The main property of <script> is language. • Eg. <script language =“javascript”> • If you don’t specify a language the default is javascript. • You can also specify a version number • <script language =“javascript”> • Always close the <script> tag, or your code will not work. • Enclose your javascript code within a html comment block <!-- -->, to make the page compatible with non-javascript browsers. 14

DOM Manipulation 15

DOM Manipulation 15

DOM Manipulation 16

DOM Manipulation 16

? איך מוסיפים אלמנטים חדשים בדף – – create. Element(element. Name) create. Text. Node(text)

? איך מוסיפים אלמנטים חדשים בדף – – create. Element(element. Name) create. Text. Node(text) append. Child(new. Child) remove. Child(node) <ol> הוספת פריט ברשימה : דוגמא var list = document. get. Element. By. Id("list 1") ; var newitem = document. create. Element("li"); var newtext = document. create. Text. Node("text"); newitem. append. Child(newtext); list. append. Child(newitem); <ol id=“list 1”> <li> some items </li> </ol> id = “list 1” - ( חילוץ האלאמנט )קודקוד( ש 1) <li> ( יצירת אלמנט 2) ( יצירת אלמנט עם טקסט 3) <li>some item</li> התוצאה : (2) ( ל 3) ( הוספת הבן 4) (1) ( ל 2) ( הוספת 5) <ol id=“list 1”> <li> some items </li> <li> new item</li> </ol>

Dynamic HTML With the object model, Java. Script gets all the power it needs

Dynamic HTML With the object model, Java. Script gets all the power it needs to create dynamic HTML: • Java. Script can change all the HTML elements in the page • Java. Script can change all the HTML attributes in the page • Java. Script can change all the CSS styles in the page • Java. Script can remove existing HTML elements and attributes • Java. Script can add new HTML elements and attributes • Java. Script can react to all existing HTML events in the page • Java. Script can create new HTML events in the page Example: https: //jsfiddle. net/Lbnhs 8 aa/1/ 19

Elements can be referenced • by their id or name (this is the easiest

Elements can be referenced • by their id or name (this is the easiest way, but you need to make sure a name is unique in the hierarchy). • You pick up an arbitrary id or name for an element, a bit like a variable name (we’ll see later the difference id/name) • by their numerical position in the hierarchy • by walking the array that contains them, say get the 3 rd child • by their relation to parent, child, or sibling (parent. Node, previous. Sibling, next. Sibling, first. Child, last. Child or the child. Nodes array • By class • An element can be assigned any number of class. A class is similar to an arbitrary group of elements in the document (just add the class to any element you want in the group) 20

A div example • <div> is a HTML element container (<span> also, what is

A div example • <div> is a HTML element container (<span> also, what is the difference? ). We use it to wrap elements (we create a DOM element) • <div id=”mydiv”> This is some simple text to display. </div> • the div is an element with an id of mydiv that must be UNIQUE in the document • It contains a text element, which can be referenced by child. Nodes[0] (child. Node being an array of all childen of a node • So the text in the div is not a value of the div, but rather the value of the first (and only) child. Node of the div 21

Referencing by Id • For example you find out if a checkbox is checked:

Referencing by Id • For example you find out if a checkbox is checked: • document. get. Element. By. Id("radio. LC"). checked • Returns true/false if the checkbox is checked/unchecked • document. get. Element. By. Id(”my. Div") This is a predefined function that makes use of the id that can be defined for any element in the page • An id must be unique in the page, so only one element is ever returned by this function • The argument to get. Element. By. Id specifies which element is being requested (parameter is the id value) 22

Finding an element by tag name • find all <p> elements: • var x

Finding an element by tag name • find all <p> elements: • var x = document. get. Elements. By. Tag. Name("p"); Will return all <p> elements as an array • Live example: • https: //www. w 3 schools. com/js/tryit. asp? filename=tryjs_dom_getelementsb ytagname 2 23

Find element by class name • The ”class” attribute of an element allows fetching

Find element by class name • The ”class” attribute of an element allows fetching and applying functions to an arbitrary set of elements in the document • Many HTML elements can belong to a class, all you have to do is add the class name in the class attribute. The class names are arbitrarily defined and used by Javascript and CSS. • For example if you have the following HTML: <p class=”important”>This is an important message</p> <h 1 class=“important someclass”>Notes</h 1> <p> some other paragraph</p> • And the following Javascript var x = document. get. Elements. By. Class. Name(”important"); • You fetch 2 elements (the <p> and <h 1>) • Live example: • https: //www. w 3 schools. com/js/tryit. asp? filename=tryjs_dom_getelementsbyclassname 24

Find element by CSS selector • Get the first element in the document with

Find element by CSS selector • Get the first element in the document with class="example": • document. query. Selector(". example"); • Change the text of an element with id="demo": • document. query. Selector("#demo"). inner. HTML = "Hello World!"; • Get the first <p> element in the document where the parent is a <div> element. • document. query. Selector("div > p"); 25

Examples of events • Form element events • change, focus, blur • Network events

Examples of events • Form element events • change, focus, blur • Network events • online, offline • View events • resize, scroll • Clipboard events • cut, copy, paste • Keyboard events • keydown, keypress, keypup • Mouse events • mouseenter, mouseleave, mousemove, mousedown, mouseup, click, dblclick, select 26

Hiding an element • Applying a CSS property • Hide but leave elements in

Hiding an element • Applying a CSS property • Hide but leave elements in its position document. get. Element. By. Id("my. P"). style. visibility = "hidden"; • The result is equivalent to <div id="my. P" style="display: hidden; "> </div> • Hide document. get. Element. By. Id("my. DIV"). style. display = "none"; 27

Using CSS classes to modify the DOM • Example: accessing the image attribute of

Using CSS classes to modify the DOM • Example: accessing the image attribute of HTML tag <img> • HTML: <img src="logo. png"> • Javascript: const img = document. query. Selector('img'); img. has. Attribute('src'); // returns true img. get. Attribute('src'); // returns ”logo. png" img. remove. Attribute('src'); // remove the src attribute and value img. set. Attribute('src', 'ghost. jpg'); // replaces image 28

Using classes to modify the DOM • Technique: define a bunch of useful CSS

Using classes to modify the DOM • Technique: define a bunch of useful CSS classes (states of your elements), for example an “error” style • Apply/remove the class when needed const active. Div = document. query. Selector('. active'); active. Div. class. List. add('hidden'); // active. Div. class. List. remove('hidden'); active. Div. class. List. toggle('hidden'); active. Div. class. List. replace('active', class Add the hidden class // Remove the hidden class // Switch between hidden true and false 'warning'); // Replace active class with warning • Why is it better than directly applying the style? • Example: • https: //www. w 3 schools. com/howto/tryit. asp? filename=tryhow_js_remove_class 29

A note about efficiency • A selector is a search operation over a tree

A note about efficiency • A selector is a search operation over a tree • It can be expensive! • If you use the same selector again and again in your code and the result is the same, then cache it! (use a variable and store the result) • Var mymenu = document. get. Element. By. Id(“themenu”); • If you have a complex selector, try to help the search by giving a parent node that limits the search to a subtree: • For example write document. query. Selector('menu. item') instead of document. query. Selector('. item'); 30

When is the DOM available? • The browser needs to parse the entire HTML

When is the DOM available? • The browser needs to parse the entire HTML document to build the DOM! • What is the output of the following? <script> document. get. Element. By. Id('elem'). inner. HTML = 'New content'; </script> <div id="elem">Original content</div> • Answer: error! • “cannot set property inner. HTML of undefined” • What if we swap them? Still does not work! <div id="elem">Original content</div> <script> document. get. Element. By. Id('elem'). inner. HTML = 'New content'; </script> • Why? The DOM is not built yet, therefore not available • When is the DOM available? Not necessarily when you think it is… • Answer: wait for the DOMContent. Loaded event 31

Solution • event based solution • use a function that waits for the DOM

Solution • event based solution • use a function that waits for the DOM to be available • Put all your bindings inside (add. Event. Listener) • Anything else (function definitions, variables) can be define as usual document. add. Event. Listener('DOMContent. Loaded', function(){ document. get. Element. Byid(“mybutton”). add. Event. Lisnener(“click”, clickme); // all of your event bindings go here }, false); // different syntax (we will learn that later) document. add. Event. Listener('DOMContent. Loaded', (event) => { }) 32

Using Chrome Inspector • The Chrome inspector (also in other browsers) is an essential

Using Chrome Inspector • The Chrome inspector (also in other browsers) is an essential tool to develop and debug your website • We can understand the page structure and modify it locally (for debug) • We can see the CSS and modify it locally (for debug) • We can see the network traffic between the browser and server • Put breakpoints in JS code • And more. . (in another presentation) • Demo in class + online videos 33

What’s next? • Learn Javascript and DOM manipulations • DOM: https: //www. w 3.

What’s next? • Learn Javascript and DOM manipulations • DOM: https: //www. w 3. org/DOM/ • List of events: https: //www. w 3. org/TR/DOM-Level-3 -Events/ 34