SLIDE 1 CE419 Web Programming
Session 5: JavaScript (cont'd)
1
SLIDE 2 JavaScript & The Browser
- JavaScript can be included in HTML files with <script> tag.
- Will run as soon as <script> tag is encountered as the browser reads
the HTML.
<!DOCTYPE html> <html> <head> <title>My home page</title> </head> <body> <p>Welcome!</p> <script> var name = 'Jane'; alert('Hello, ' + name); </script> </body> </html>
SLIDE 3 JavaScript & The Browser
- Including large programs directly in HTML documents is
- ften impractical.
- We can include external JS files (similar to CSS).
<!DOCTYPE html> <html> <head> <title>My home page</title> </head> <body> <p>Welcome!</p> <script src="js/greeting.js"></script> </body> </html>
Never forget this guy!
SLIDE 4 JavaScript & The Browser
- Some HTML attributes can also contain a JavaScript
program.
- Isn't JavaScript dangerous for my computer or my
health?
<button onclick="alert('Hi!');">Say Hello!</button>
SLIDE 5 Document Object Model (DOM)
- The Document Object Model (DOM) is a programming
interface for HTML (and XML) documents.
- Provides a structured representation of the document.
- The structure can be accessed from programs so that they
can change the document structure, style and content.
- Essentially, it connects web pages to scripts or
programming languages.
- Platform and language independent.
5
SLIDE 6
Document Structure
<!DOCTYPE html> <html> <head> <title>My home page</title> </head> <body> <h1>My home page</h1> <p>Hello, I am Sadjad!</p> <p>Please visit my other web site <a href="http://test.com">here</a>. </p> </body> </html>
SLIDE 7
- The nodes of every document are organized in a tree
structure, called the DOM tree.
- The global variable document gives us access to these
- bjects.
Document Object Model (DOM)
document.ELEMENT_NODE document.TEXT_NODE
SLIDE 8
SLIDE 9
SLIDE 10 Document Object Model (DOM)
- documentElement property of document refers to the
- bject representing the <html> tag.
<body> <script> heading = document.createElement("h1"); heading_text = document.createTextNode("Big Head!"); heading.appendChild(heading_text); document.body.appendChild(heading); </script> </body>
returns 'element' object.
SLIDE 11 Finding Elements
- get methods
- document.getElementById
- document.getElementsByTagName
- document.getElementsByClassName
- document.getElementsByName
- Document object collections
- anchors, forms, images, links
SLIDE 12 Finding Elements (cont'd)
- Remember CSS selectors?
- document.querySelector
- document.querySelectorAll
var elements = document.querySelectorAll("div#nav .item");
SLIDE 13 Getting Information
- For each element:
- nodeValue
Text of a text node.
The tag name
Type of the node (element, text, etc.)
The inner HTML content
SLIDE 14
Updating Elements
<!DOCTYPE html> <html> <head> <title>My home page</title> </head> <body> <h1 id="heading">My home page</h1> <p>Hello, I am Sadjad!</p> </body> </html> var e = document.getElementById("heading"); e.innerHTML = "Welcome"; e.class = "myclass"; // e.[attribute]
<h1 id="heading" class="myclass">Welcome!</h1>
e.getAttribute([name]); e.setAttribute([name], [value]);
SLIDE 15
Creating Elements
<body> <script> heading = document.createElement("h1"); heading_text = document.createTextNode("Big Head!"); heading.appendChild(heading_text); document.body.appendChild(heading); </script> </body>
SLIDE 16 Changing Style
- Using .style property of each element
var elements = document.getElementsByClassName("klass"); for(var i = 0; i < elements.length; i++) { elements[i].style.color = '#99ff00'; }
SLIDE 17
Navigating DOM Tree
SLIDE 18 Let's see DOM in action!
Showtime!
18
SLIDE 20 Events & DOM
- Every DOM element has its own addEventListener
method, which allows you to listen specifically on that element.
<button>Click me</button> <p>No handler here.</p> <script> var button = document.querySelector("button"); button.addEventListener("click", function() { console.log("Button clicked."); }); </script> target.addEventListener(type, listener);
click, drag, blur, …
SLIDE 21 Events
- click, dblclick, mouseover, mouseout
- keypress, keydown, keyup
- load, unload, resize, scroll (for window)
- focus, blur, change, submit
SLIDE 22
Adding & Remove Events
<button>Act-once button</button> <script> var button = document.querySelector("button"); function once() { console.log("Done."); button.removeEventListener("click", once); } button.addEventListener("click", once); </script>
SLIDE 23 Event Objects
- Event handler functions are passed an argument: the
event object.
<button>Click me any way you want</button> <script> var button = document.querySelector("button"); button.addEventListener("mousedown", function(event) { if (event.which == 1) console.log("Left button"); else if (event.which == 2) console.log("Middle button"); else if (event.which == 3) console.log("Right button"); }); </script>
SLIDE 24 Event Propagation
- Event handlers registered on nodes with children will also
receive some events that happen in the children.
<p>A paragraph with a <button>button</button>.</p> <script> var para = document.querySelector("p"); var button = document.querySelector("button"); para.addEventListener("mousedown", function() { console.log("Handler for paragraph."); }); button.addEventListener("mousedown", function(event) { console.log("Handler for button."); if (event.which == 3) event.stopPropagation(); }); </script>
SLIDE 25 Default Actions
- For most types of events, the JavaScript event handlers
are called before the default behavior is performed.
- You can prevent the default action.
<a href="https://developer.mozilla.org/">MDN</a> <script> var link = document.querySelector("a"); link.addEventListener("click", function(event) { console.log("Nope."); event.preventDefault(); }); </script>
SLIDE 26 Let's see event handlers in action!
Showtime!
26
SLIDE 27 Setting Timers
- The setTimeout function schedules another function to
be called later.
- clearTimeout
- setInterval, clearInterval
<script> document.body.style.background = "blue"; setTimeout(function() { document.body.style.background = "yellow"; }, 2000); </script>
SLIDE 28 Script Execution Timeline
- Things that can cause a script to start executing:
- Reading a <script> tag
- Event firing
- A few other ways
- No two scripts in a single document ever run at the same
moment.
- For time consuming tasks, look into web workers.
SLIDE 29 Browser Object Model (BOM)
- The window object represents the browser's window.
- window.innerHeight
- window.innerWidth
- window.open(), window.close()
- window.moveTo(), window.resizeTo()
SLIDE 30 Browser Object Model (cont'd)
- The window.location object can be used to get the
current page address (URL) and to redirect the browser to a new page
- location.href
- location.hostname
- location.pathname
- location.port
- location.protocol
SLIDE 31 Browser Object Model (cont'd)
- The window.history object contains the history of the
window
- history.go([n])
- history.back()
- history.forward()
SLIDE 32 TA Class
- Next week
- Subject: jQuery
SLIDE 33 References
- http://eloquentjavascript.net/
- Chapters 1, 2, 3, 4, 5, 6,12, 13, 14
- http://htmldog.com/guides/javascript/
- https://developer.mozilla.org/en-US/docs/Web/
JavaScript/Introduction_to_Object-Oriented_JavaScript
SLIDE 34 Any questions?
Thank you.
34