CE419 Session 5: JavaScript (cont'd) Web Programming � 1
JavaScript & The Browser • JavaScript can be included in HTML files with <script> tag. <!DOCTYPE html> <html> <head> <title>My home page</title> </head> <body> <p>Welcome!</p> <script> var name = 'Jane'; alert('Hello, ' + name); </script> </body> </html> • Will run as soon as <script> tag is encountered as the browser reads the HTML.
JavaScript & The Browser • Including large programs directly in HTML documents is often 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> Never forget this guy! </html>
JavaScript & The Browser • Some HTML attributes can also contain a JavaScript program. <button onclick="alert('Hi!');" >Say Hello!</button> • Isn't JavaScript dangerous for my computer or my health? • Sandboxing.
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
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>
Document Object Model (DOM) • The nodes of every document are organized in a tree structure, called the DOM tree. • The global variable document gives us access to these objects. document.ELEMENT_NODE document.TEXT_NODE
Document Object Model (DOM) • documentElement property of document refers to the object representing the <html> tag. <body> returns 'element' object. <script> heading = document .createElement("h1"); heading_text = document .createTextNode("Big Head!"); heading.appendChild(heading_text); document .body.appendChild(heading); </script> </body>
Finding Elements • get methods • document. getElementById • document. getElementsByTagName • document. getElementsByClassName • document. getElementsByName • Document object collections • anchors, forms, images, links
Finding Elements (cont'd) • Remember CSS selectors? • document.querySelector • document.querySelectorAll var elements = document.querySelectorAll("div#nav .item");
Getting Information • For each element: • nodeValue Text of a text node. • nodeName The tag name • nodeType Type of the node (element, text, etc.) • innerHTML The inner HTML content
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> var e = document.getElementById("heading"); </html> e.innerHTML = "Welcome"; e.class = "myclass"; // e. [attribute] <h1 id="heading" e.getAttribute( [name] ); class="myclass">Welcome!</h1> e.setAttribute( [name], [value] );
Creating Elements <body> <script> heading = document .createElement("h1"); heading_text = document .createTextNode("Big Head!"); heading.appendChild(heading_text); document .body.appendChild(heading); </script> </body>
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'; }
Navigating DOM Tree
Showtime! Let's see DOM in action! � 18
Events • Polling • Event Listener
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, …
Events • click, dblclick, mouseover, mouseout • keypress, keydown, keyup • load, unload, resize, scroll (for window ) • focus, blur, change, submit
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>
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>
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>
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>
Showtime! Let's see event handlers in action! � 26
Setting Timers • The setTimeout function schedules another function to be called later. <script> document.body.style.background = "blue"; setTimeout(function() { document.body.style.background = "yellow"; }, 2000); </script> • clearTimeout • setInterval, clearInterval
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 .
Browser Object Model (BOM) • The window object represents the browser's window. • window.innerHeight • window.innerWidth • window.open(), window.close() • window.moveTo(), window.resizeTo()
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
Browser Object Model (cont'd) • The window.history object contains the history of the window • history.go( [n] ) • history.back() • history.forward()
TA Class • Next week • Subject: jQuery
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
Thank you. Any questions? � 34
Recommend
More recommend