650 likes | 794 Vues
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
E N D
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 • Document object • Allows access to other objects representing elements on a Web page
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
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()
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
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
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.
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
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"
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
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.
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)
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
Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"><br /> Phone: <input name="phone"><br /> Email: <input name="email"><br /> </form>
Forms and JavaScript document.formname.elementname.value Thus: document.addressform.yourname.value document.addressform.phone.value document.addressform.email.value
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>
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";
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>
Forms and JavaScript document.getElementById("elementname").value Thus: document.getElementById("yourname").value document.getElementById("phone").value document.getElementById("email").value
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
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>
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
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
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"; }
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.
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.
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".
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
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
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
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
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
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
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
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
JavaScript Events Timers and Images
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…)
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
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>
Some Events (a small sample) onUnLoad onLoad onClick onMouseUp onMouseDown onDblClick onMouseOver Window events Button events Link events
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 …
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>
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
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
Javascript Timers • One-time timer setTimeout(callback, milliseconds) • Repeated Timer x = setInterval(callback, milliseconds) • Canceling the timer clearInterval(x)
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.
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>
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!”); }