1 / 64

JavaScript Events, DOM & Forms

onClick , innerHTML , getElementById. JavaScript Events, DOM & Forms. JavaScript Events, working with the Document Object Model, working with forms. Understanding the HTML Document Object Model (cont’d.). JavaScript accesses individual elements on a Web page Can change them individually

Download Presentation

JavaScript Events, DOM & Forms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. onClick, innerHTML, getElementById JavaScript Events, DOM & Forms JavaScript Events, working with the Document Object Model, working with forms

  2. Understanding the HTML Document Object Model (cont’d.) • JavaScript accesses individual elements on a Web page • Can change them individually • Document object • Allows access to other objects representing elements on a Web page

  3. The DOM • “The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use.” Wikipedia You can add and subtract DOM elements on the fly You can change the properties and contents of DOM elements on the fly

  4. HTML Document Object Model (HTML DOM) 10 nodes

  5. Accessing Nodes • JavaScript has several methods for accessing nodes; we are going to look at: getElementById(id) getElementsByName(name) getElementsByTagName(tag name) getAttribute() setAttribute() document.forms[index].fieldname.value = … document.formname.fieldname.value= … innerHTML()

  6. Document Object Model • The Document Object Model provides access to every element in a document. Because of that access, any element may be modified by a snippet of JavaScript. • Elements are easily accessed by use of an id attribute and the getElementById method of the document object. • Note that the value of the id attribute must be unique within a given document. I.e., You cannot have two elements with the same id within the same document. • The script changes the color of the header element <html> <body> <h1 id="header">My header</h1> <script type="text/javascript"> document.getElementById('header').style.color = "red" </script> </body> </html> Any element, which contains an id attribute, may be referenced by the getElementById() method. Pass it the value of the id attribute and you may then reference any properties, methods, or collections of the element. I.e., the text color of the element, whose id is 'header', is referenced by document.getElementById('header').style.color

  7. Modifying Elements with the innerHTML Property • innerHTML property • Sets and retrieves the content of a specified element • Originally introduced by Microsoft into Internet Explorer browsers • Property allows you to retrieve and modify the contents of almost any element • Without having to reload the entire Web page

  8. DOM: InnerHTML • Use innerHTML function to access the contents—the code—contained in an object. • For example, given a paragraph whose id = "sample", its innerText and innerHTML may be accessed via: document.getElementById('sample').innerHTML • By manipulating the innerHTML property you can change, dynamically, the text on a page (without reloading the page). • The content of an object is interpreted as HTML with the innerHTML function. • innerHTML = <b>inner text</b>" would display as inner text.

  9. DOM: InnerHTML Recall that the <div></div> tag is often used To define a region within a page so that it can encompass several page elements, such as several paragraphs or a paragraph and a table. The innerHTML, style properties, etc. of the entire div can be changed. I.e., change the div (id="d1") to red; to purple; to yellow; change the innerHTML of the div. <script type="text/javascript"> function ChangeInnerHTML(theID, theHTML) { if (typeoftheHTML == "undefined") { theHTML = window.prompt("Please specify innerHTML", "<b>hello world</b>"); } document.getElementById(theID).innerHTML = theHTML; } function ChangeColor(theID, theColor) { document.getElementById(theID).style.backgroundColor = theColor; } </script> <div id="d1"> </div> change the div (id="d1") to <a href="javascript:ChangeColor('d1','red');">red</a>; … <a href="javascript:ChangeInnerHTML('d1');">change the innerHTML of the div</a>. changeDiv.html

  10. Example <body> <textarea id="box1"></textarea> <input type="button" value="update" onclick="update()" /> <p id="message">This is a message box.</p> </body> id="box1" id="message"

  11. Example <head> <script> function update(){ document.getElementById("message").innerHTML = document.getElementById("box1").value; } </script> </head> • Replace the content of a tag with text or html code

  12. DOM: Forms - Form Fields • You can use the DOM to get the value of a form field, or to set the value of a form field. • Assign a name or an ID to each form field. • use the value attribute to access the current value.

  13. HTML Forms and JavaScript • JavaScript is very good at processing user input in the web browser • HTML <form> elements receive input • Forms and form elements have unique names • Each unique element can be identified • Use JavaScript Document Object Model (DOM)

  14. DOM Example • Access individual elements of a HTML document. • Easy to use if you identify or name all entities: • Forms, fields, images, etc. <FORM ID=myform NAME=myformACTION=… > Please Enter Your Age: <INPUT TYPE=TEXT ID=age NAME=age><BR> And your weight: <INPUT TYPE=TEXT ID=weight NAME=weight><BR> </FORM> Using JavaScript you can get the value of the age input field: document.myform.age.value

  15. Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"><br /> Phone: <input name="phone"><br /> Email: <input name="email"><br /> </form>

  16. Forms and JavaScript document.formname.elementname.value Thus: document.addressform.yourname.value document.addressform.phone.value document.addressform.email.value

  17. Using Form Data Personalising an alert box <form name="alertform"> Enter your name: <input type="text" name="yourname"> <input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);"> </form>

  18. Accessing Elements by ID • Extremely useful if programmer needs to work with collections of elements • Having the same name attribute or of the same type • getElementById() method • Returns the first element in a document with a matching id attribute • Provides direct access to a node with the id passed to it: varoElement = document.getElementById("myElement") • Which would then allow us to do this: oElement.style.backgroundColor = "#FF0000";

  19. Naming Form Elements in HTML: IDs <form id="addressform"> Name<input id="yourname" name="yourname"><br /> Phone: <input id="phone" name="phone"><br /> Email: <input id="email" name="email"><br /> </form>

  20. Forms and JavaScript document.getElementById("elementname").value Thus: document.getElementById("yourname").value document.getElementById("phone").value document.getElementById("email").value

  21. DOM: Forms - Form Field Example Name: <INPUT ID=nfield TYPE=TEXT><br/> <INPUT TYPE=BUTTON VALUE="Check" onClick="validate();"> <SCRIPT> function validate() { fld = document.getElementById("nfield"); if (fld.value != "Dave") { alert("The name you typed is wrong"); fld.value="Dave"; } } <SCRIPT> formexample.html

  22. Simple Form Access (setting a value)  function toggle() { if(document.simpleform.simpleinput.value == "Hello") document.simpleform.simpleinput.value = "World"     else document.simpleform.simpleinput.value = "Hello"     }  Or     function toggle() {           if(document.getElementById("simpleinput").value == "Hello") document.getElementById("simpleinput").value = "World";           else document.getElementById("simpleinput").value = "Hello";     } <form name="simpleform"> <input type="text" name="simpleinput" value="Hello"> <input type="button" name="simplebutton" value="Go" onClick="toggle()"> </form> Or <form id="simpleform" action="DOM -- SimpleFormAccess.html"> <div>   <input type="text" id="simpleinput" value="Hello" />   <input type="button" id="simplebutton" value="Go" onclick="toggle()" /> </div> </form>

  23. Accessing Elements by Name • getElementsByName() method • Returns array of elements with a name attribute matching a specified value • Method always returns an array • Even if only one element

  24. Document Object – getElementsByName <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("myInput"); alert(x.length); } </script> </head> <body> <input name="myInput" type="text" size="20" /><br /> <input name="myInput" type="text" size="20" /><br /> <input name="myInput" type="text" size="20" /><br /> <br /> <input type="button" onclick="getElements()" value="How many elements named 'myInput'?" /> </body> </html> • Result: will display 3

  25. Accessing Elements by Tag Name • getElementsByTagName() method • Returns array of elements matching a specified tag name • Method always returns an array • Even if only one element • Provides access to all nodes of "tagName" varoDivs = document.getElementsByTagName("div"); Which would allow us to do this: vari=oDivs.length; while(i-- > 0) { oDivs[i].className = "myNewClass"; }

  26. Accessing Document Elements • getAttribute() accepts as a parameter an attribute of an element. • Once JavaScript has the attribute, JavaScript can change its value. • setAttribute() accepts as parameters the attribute you would like to change and the value to which you would like to change it.

  27. getElementById & getElementsByTagName We can use these two methods in conjunction. var oElement = document.getElementById("myElement"); var oDivs = oElement.getElementsByTagName("div"); This will give us only the DIV elements that descend from myElement.

  28. Exercise • Create a web page that looks as follows: When the user clicks "Generate Song", the phrase "round and round" will be repeated the specified number of times after "The wheels on the bus go".

  29. The Wheels On The Bus Go… <div> Times: <input type="text" id="times" /><br /> <input type="button" value="Generate Song" onclick="generate();" /> <p id="output"> </p> </div> HTML function generate() { var times = document.getElementById("times").value; var text = "The wheels on the bus go "; for (var i = 1; i <= times; i++) { text = text + "round and round "; } document.getElementById("output").innerHTML = text; } JavaScript

  30. The Wheels On The Bus Go… • Can shorten text = text + ... to text += ... function generate() { var times = document.getElementById("times").value; var text = "The wheels on the bus go "; for (var i = 1; i <= times; i++) { text += "round and round "; } document.getElementById("output").innerHTML = text; } JavaScript

  31. Create a web page that looks as follows (example values filled in): When the user clicks "Generate Sentences", the text will be repeated the specified number of times. Exercise

  32. Solution <div> Text: <input type="text" id="text" /><br /> Times: <input type="text" id="times" /><br /> <input type="button" value="Generate Sentences" onclick="generate();" /> <p id="output"> </p> </div> HTML function generate() { var times = document.getElementById("times").value; var sentence = document.getElementById("text").value; var text = ""; for (var i = 1; i <= times; i++) { text += sentence + "<br />"; } document.getElementById("output").innerHTML = text; } JavaScript

  33. Exercise: Radio Buttons <label> <input type="radio" name="cards" id="cards1" value="MasterCard" onchange="showCard(1);" />MasterCard </label> <label> <input type="radio" name="cards" id="cards2" value="Visa" onchange="showCard(2);" />Visa </label> <label> <input type="radio" name="cards" id="cards3" value="Discover" onchange="showCard(3);" />Discover </label> HTML function showCard(num) { var value = document.getElementById("cards" + num).value; alert("You picked: " + value); } JavaScript

  34. Exercise: Radio Buttons <label> <input type="radio" name="cards" id="cards1" value="MasterCard" onchange="showCard();" />MasterCard </label> <label> <input type="radio" name="cards" id="cards2" value="Visa" onchange="showCard();" />Visa </label> <label> <input type="radio" name="cards" id="cards3" value="Discover" onchange="showCard();" />Discover </label> • It is possible to use the same parameter-less function. • Use document.getElementById("<ID>").checked to see if each radio button is activated • The checked attribute is a Boolean value (true or false). HTML

  35. Exercise: Radio Buttons function showCard() { if (document.getElementById("cards1").checked) { var value = document.getElementById("cards1").value; alert("You picked: " + value); } if (document.getElementById("cards2").checked) { var value = document.getElementById("cards2").value; alert("You picked: " + value); } if (document.getElementById("cards3").checked) { var value = document.getElementById("cards3").value; alert("You picked: " + value); } } JavaScript

  36. Exercise: Radio Buttons • Can loop over element IDs • Although the previous slide is acceptable as a solution in this class, you should learn to make the computer do most of the work for you as above. function showCard() { for (vari = 1; i <= 3; i++) { varidToTry = "cards" + i; if (document.getElementById(idToTry).checked) { var value = document.getElementById(idToTry).value; alert("You picked: " + value); } } } JavaScript

  37. JavaScript Events Timers and Images

  38. JavaScript Events • Events are associated with many elements of a page • <li onclick=“funct(1)”>blah…</li> • Events associated with click, double-click, focus, errors keyboard, hover, mousemove, resize, scroll,… • return false to cancel the default action (submitting a form, following a link, etc.) • Events will be fired all the way up the chain (e.g. li, then ul, then div, then document…)

  39. Event Handlers • With an event handler, you can do something with an element when an event occurs, i.e., when the user clicks an element, when the page loads, when a form is submitted, timed events etc. • An event handler may be included within any XHTML tag; however, not all tags support all event handlers. • The example below defines a header that turns red when a user clicks on it. <h1 onclick="this.style.color='red'"> Click on this text</h1> • You can also add a script in the head section of the page and then call the function from the event handler: <html> <head> <script type="text/javascript"> function changecolor() { document.getElementById('header') .style.color="red" } </script> </head> <body> <h1 id="header" onclick="changecolor()"> Click on this text</h1> </body> </html> changeHeader.html

  40. Buttons • You can associate buttons with JavaScript events • buttons in HTML forms <FORM> <INPUT TYPE=BUTTON VALUE="Don't Press Me" onClick="alert('now you are in trouble!')"> </FORM>

  41. Some Events (a small sample) onUnLoad onLoad onClick onMouseUp onMouseDown onDblClick onMouseOver Window events Button events Link events

  42. Example: onLoadevent • The onLoad event is triggered when an element is loaded by the browser. • You can put an onLoadhandler in the BODY tag: <BODY onLoad="alert('Welcome');"> <H1>A title</H1> <P>Here is a paragraph …

  43. Another onLoad example <SCRIPT> function start() { window.setInterval("updateTime()",1000); } var seconds=0; function updateTime() { seconds++; document.getElementById("time").innerHTML = seconds; } </SCRIPT> <BODY onLoad="start();"> <H1>Sample Document</H1> <H3>You have been here <B ID=time>0</B> seconds.</H3>

  44. Timers

  45. Working with Timeouts and Intervals • To have some JavaScript code execute repeatedly, without user intervention, you use JavaScript’s timeout and interval methods • The setTimeout() method is used in JavaScript to execute code after a specific amount of time has elapsed • The clearTimeout() method is used to cancel a setTimeout() method before its code executes

  46. Working with Timeouts and Intervals • Two other JavaScript methods that create code that executes automatically are the setInterval() method and the clearInterval() method • The setInterval() method is similar to the setTimeout() method, except that it repeatedly executes the same code after being called only once • The clearInterval() method is used to clear a setInterval() method call in the same fashion that the clearTimeout() method clears a setTimeout() method call

  47. Javascript Timers • One-time timer setTimeout(callback, milliseconds) • Repeated Timer x = setInterval(callback, milliseconds) • Canceling the timer clearInterval(x)

  48. setTimeout • var t=setTimeout("javascriptstatement",milliseconds); • The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name. • The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()". • The second parameter indicates how many milliseconds from now you want to execute the first parameter. • Note: There are 1000 milliseconds in one second.

  49. Timers • JavaScript provides easy access to a timer via the window functions setTimeout(‘function()’, millisecs) and clearTimeout(var) <head> <script language="javascript" type="text/javascript"> function delayedAlert() { var timer = window.setTimeout("alert('Time is up')", 5000); } </script> </head> <body <input type="button" value="Start timer" onclick="delayedAlert()" /> </form> </body>

  50. setTimeout function • Same as calling any other function with parameters: • setTimeout(function, delay); • function is the function to call after delay milliseconds has passed function startTimer() { setTimeout(alertBox, 1000); } function alertBox() { alert(“Hello!”); }

More Related