HTML 5 Jim Warren content based largely in
HTML 5 Jim Warren (content based largely in W 3 C sources)
Learning outcomes • Describe and apply the capabilities considered ‘DHTML’ using HTML 5 approaches • Understand the Document Object Model (DOM) for Web pages • Be able to write Javascript functions • Combine DOM and Javascript (and CSS) to enable dynamic content and embed functionality in Web pages • Implement drag&drop and other on-screen movement in Web pages 2
What is DHTML? • You don’t give a. dhtml extension or such • Written in HTML or XHTML markup • Just techniques using • Javascript • Cascading Style Sheets (CSS) • Document Object Model (DOM) • DHTML effects include • • Event detection (e. g. mouse-over) Pop-up windows Form validation Turning objects visible/invisible the human 1 3 • Dynamic HTML • It’s not a language
What is HTML 5? • <video>, <audio> and <canvas> elements • Scalable vector graphics (SVG) • Math. ML • Offers various APIs including drag-and-drop and Web storage (although technically the latter is now outside HTML 5) • Even defines some processing for invalid documents for greater uniformity in responses to syntax errors • ‘Candidate recommendation’ of W 3 C as of Dec 2012 • But already widely supported and expected to be a ‘Recommendation’ in 2014 the human 1 4 • Subsumes HTML 4, XHTML 1 and DOM Level 2 HTML • Better handling for multimedia and graphical content to avoid resorting to proprietary plug-ins
Why is this useful? • Portability • Run same code on anything with a Web browser (still some need for browser-specific coding, but less every year) • Maximizes client-side interpretation • E. g. to run appropriately on a wide variety of devices • Searchability and openness to screen readers • Make as much of your content as possible available for machine processing • Google can’t reach inside an applet to find and index your content (and that’s how people find things nowadays) • Growing popularity • Probably because of the above reasons, and also it’s getting to be powerful enough to do most of what you want without resorting to Java, . Net, Objective-C or the like 1 -5
The Document Object Model (DOM) • • The HTML elements as objects The properties of all HTML elements The methods to access all HTML elements The events for all HTML elements • Tree-structured • Mostly access using Javascript http: //www. w 3 schools. com/js/js_htmldom. asp the human 1 6 • The HTML DOM is a standard object model and programming interface for HTML. It defines:
Javascript is a scripting language very broadly supported in browsers • • • Not really officially, or syntactically, all that related to Java: was officially called Live. Script when it first shipped in beta releases of Netscape Navigator 2. 0 in September 1995 Standardized through European Computer Manufacturers Association (ECMA) Dynamically typed with first-class functions (functions are themselves objects) Use the <script> tag to indicate a block of Javascript in your HTML 7
Javascript language example • Syntax reminiscent of C and Java • But notice you don’t need to declare the type of a variable • System guesses based on use • Not great for quality <html> assurance, but easy <body> • alert pops up a dialog • . write (a method of the DOM document object) tacks content onto the end of the HTML <h 1>Javascript-generated output below</h 1> <script> a=2; /* note implicit typing */ a++; fname="Tom"; lname="Hanks"; if (fname=="Tom") {alert("Nice name, "+fname)}; document. write("a="+a); </script> </body> </html> 1 -8
Referencing the DOM with Javascript • In the DOM, HTML elements are objects with properties and methods • You can set a property value in HTML in the tag declaration (e. g. the id property of the paragraph element is set to “intro” in the example) <html> • When the Javascript <body> is run, we use the <p id="intro">Hello World!</p> document’s method get. Element. By. Id to reference an element by name (id) and then access its contents through its inner. HTML property <script> var txt=document. get. Element. By. Id("intro"). inner. HTML; document. write("""+txt+"""); </script> </body> </html> Using escape character to put a doublequote in double-quotes. So this line simply adds “Hello World!” (include quotes) at the bottom of the page 1 -9
Form validation • HTML 5 gives you convenient types form input (see below) • Other convenient types: date, time, password • Note each browser brand will display a bit differently • Use CSS ‘pseudoclasses’ to control appearance based on whether input meets the form’s validation <style> /* really ugly style for illustration */ input: required: invalid { border-color: FF 0000; } input: required: valid { border-color: 00 FF 00; } </style> <h 1>HTML 5 forms</h 1> <form> Appearance in Chrome Your Name: <input type="text" name="name" required> Email Address: <input type="email" name="email" required placeholder="Enter a valid email address"> Website: <input type="url" name="website" required pattern="https? : //. +"> Age: <input type="number" size="6" name="age" min="18" max="99" value="21"> Satisfaction: <input type="range" size="2" name="satisfaction" min="1" max="5" value="3"> <input type="submit" value="Submit" /> </form> 1 -10
More CSS for validation feedback • Can use CSS to specify icons that appear to mark various validation statuses http: //websemantics. co. uk/online_tools/image_to_data_uri_convertor/ Can specify image as [long] inline character string rather than needing an auxiliary file <STYLE TYPE="text/css"> input: required: invalid, input: focus: invalid { background-image: url('data: image/png; base 64, i. VBO -- //. . . // -- Qm. CC'); background-position: right; background-repeat: no-repeat; -moz-box-shadow: none; } Brand-specific property (for Mozilla in this case) [this specific one is obsolete from Mozilla v 13, but never mind] 1 -11
Another form control • Radio buttons • Multiple input controls all relating to the same form variable Note use of label controls to be more explicit that the content serves as captions • In this case we set the value of rad. Size to “small”, “medium” or “large” <label>Size: </label> <input type = "radio" name = "rad. Size" id = "size. Small" value = "small" checked = "checked" /> <label for = "size. Small">small</label> <input type = "radio" name = "rad. Size" id = "size. Med" value = "medium" /> <label for = "size. Med">medium</label> <input type = "radio" name = "rad. Size" id = "size. Large" value = "large" /> <label for = "size. Large">large</label> 1 -12
Handling events • You can give any button, including the submit input field of a form, an onclick value • Name it to a Javascript function you’ve declared higher in the HTML • Can pass data to this event handler (e. g. pass ‘this’, the button itself) Here we pull out the value of an input field (the one with name=“name”) from the form <head> <script> function show_data(element) { form=element. form; /* the button's form */ txt=form. elements. named. Item("name"). value; alert("The name is: "+txt); } </script> </head>. . . <input type="submit" onclick="show_data(this)" value="Submit button"> </form> 1 -13
Handling event (contd. ) • For our prototyping in Assignment 3, might be just as well if we don’t use a ‘real’ submit button • Any button can invoke an event handler, and we can still use the DOM to find the <head> values on the <script> function show_data() input controls { • And there are other events than onclick • E. g. onmouseover, onmouseout • See form=document. get. Element. By. Id("myform"); txt=form. elements. named. Item("name"). value; alert("The name is: "+txt); } </script> </head>. . . <form id="myform">. . . </form> <button onclick="show_data()">A button</button> http: //www. w 3 schools. com/js/tryit. asp? filename=tryjs_events_mouseover 1 -14
Nasty but Handy Javascript Dialogs • Three types • Alert • Confirm • Prompt It’s “window. confirm” but you can leave the window class off <script> var r=confirm("Press a button"); if (r==true) {x="You pressed OK!"; } else {x="You pressed Cancel!"; } </script> 1 -15
Dynamically changing your page through the DOM • Simply change the inner. HTML through assignment in a script Optional default value <div id="demo"></div>. . . <script> person = prompt("Please enter your name", "Harry Potter"); if (person!=null) {x = "Hello " + person + "! How are you today? "; document. get. Element. By. Id("demo"). inner. HTML=x; } </script> Any piece of the HTML that you can get a handle on, you can change to something else! 1 -16
Dynamically changing visibility • Visibility is a handy property for achieving interactive effects <script> function show_data() { form=document. get. Element. By. Id("myform"); txt=form. elements. named. Item("vis"). value; document. get. Element. By. Id("demo"). style. visibility=txt; } Setting the form variable vis </script> to actual value needed for </head>. . . DOM visibility property <form id="myform"> <label>Visibility: </label> <input type = "radio" name = "vis“ Using onchange id = "vis. Yes" value = "visible" onchange="show_data(); "/> event for immediate <label for = "vis. Yes">Yes</label> <input type = "radio" name = "vis“ response id = "vis. No" value = "hidden" checked = "checked" onchange="show_data(); "/> <label for = "vis. No">No</label>. . . <div id="demo" style="visibility: hidden">Boo!</div> • Even hidden elements get allocated space; also consider the display property http: //www. w 3 schools. com/jsref/prop_style_display. asp 1 -17
Popping up browser windows • Gives more control than a modal dialog • Note can be an annoying (like pop-up ads) kind of behaviour • Also the browser settings might block it! • Can open a new browser window with a URL (1 st parameter of window. open) or just write into its DOM to create it dynamically 3 rd parameter is window ‘specs’ including what controls to enable <script> var my. Window = window. open("", "Msg. Window", "width=200, height=100"); my. Window. document. write("<title>Child</title>"); my. Window. document. write("<p>This is 'Msg. Window'. I am 200 px wide and 100 px tall!</p>"); my. Window. document. write("<button onclick="window. close(); ">Close</button>"); </script> 1 -18 http: //www. w 3 schools. com/jsref/met_win_open. asp
Embedding data in a Web page • User-defined attributes • HTML 5 endorses hidden data using custom attributes as long as you start your attribute names with ‘data-’ <div id='strawberry-plant' data-fruit='12'></div>. . . var plant = document. get. Element. By. Id('strawberry-plant'); var fruit. Count = parse. Int(plant. get. Attribute('data-fruit'))-1; plant. set. Attribute('data-fruit', fruit. Count. to. String()); // Pesky birds Note use of to. String and parse. Int (or whatever you need, eg parse. Float) to move in and out of text 1 -19
Arrays of data from DOM • If you want to get multiple elements at a time you might like get. Elementsby. Name <div id='strawberry-plant 1' name="plant" data-fruit='12'></div> <div id='strawberry-plant 2' name="plant" data-fruit='8'></div> <div id='blackberry-plant 1' name="plant" data-fruit='25'></div>. . . Returns an array var plants=document. get. Elements. By. Name("plant"); alert(plants. length); alert(plants[2]. get. Attribute('data-fruit')); 3 25 1 -20
Getting data back from a child window • Use window. opener in the child window to reference its parent <title>Parent Window</title> </head><body> <p id="intro">Hello World!</p> <script> var my. Window = window. open("", "Msg. Window", "width=300, height=200"); txt="<head><title>Child</title>"; txt+="<script>function sender() {"; txt+="dest=window. opener. document. get. Element. By. Id("intro"); "; txt+="dest. inner. HTML=document. get. Elements. By. Name("msg")[0]. value; "; txt+="window. close(); }"; txt+="</script></head>"; txt+="<p>This is 'Msg. Window'. I am 300 px wide and 200 px tall!</p>"; txt+="Type a message: <input type="text" name="msg"> "; txt+="<button onclick="sender()">Close</button>"; my. Window. document. write(txt); </script> I just built the child window’s HTLM into a string, with a function named sender that resets the parent’s intro object with the message 1 -21
Web Storage • HTML 5 Web Storage provides two new objects for storing data on the client • window. local. Storage - stores data with no expiration date • code. session. Storage - stores data for one session (data is lost when the tab is closed) • Faster and larger data limit than old method, ‘cookies’ • http: //www. w 3 schools. com/html 5_webstorage. asp 22
Web Storage example • session. Storage has set. Item and get. Item methods • Give items whatever name you like (first parameter) // Store value on the browser for duration of the session var names = []; names[0] = prompt("New member name? "); names[1] = prompt("Another new member name? "); session. Storage. set. Item("name_store", JSON. stringify(names)); . . . Note these JSON helper methods to push an array in and out of a string // Retrieve value (persists until tab is closed) var div 2 = document. get. Element. By. Id("div 2"); var retr_names = []; /*retr_names[1]="bob"; */ retr_names=JSON. parse(session. Storage. get. Item("name_store")); /*alert(retr_names[1]); */ div 2. inner. HTML="Name 1: "+retr_names[0]+" Name 2: "+retr_names[1]; Sets the content of the element with id=div 2 to the two interactively input names 1 -23
Drag & drop • A key feature of ‘direct manipulation’ interfaces popularised by the Macintosh • Part of HTML 5 standard; to use it, define: • What can receive a drop • Something as draggable • What data to pick up for drag • How to process the drop http: //www. w 3 schools. com/html 5_draganddrop. asp 24
Drap & drop code <style type="text/css"> div. abox {float: left; width: 250 px; height: 70 px; padding: 10 px; border: 2 px solid #aaaaaa; margin: 5 px} </style> Define a style for a class of div <script> called ‘abox’ function allow. Drop(ev) {ev. prevent. Default(); } function drag(ev) {ev. data. Transfer. set. Data("Text", ev. target. id); } Define event handlers function drop(ev) { ev. prevent. Default(); var data=ev. data. Transfer. get. Data("Text"); ev. target. append. Child(document. get. Element. By. Id(data)); } </script> </head><body> <p>Drag the W 3 Schools image into the rectangle: </p> Make 3 boxes, the first set to receive a drop, the others grey; define a draggable image <div id="div 1" class="abox" ondrop="drop(event)" ondragover="allow. Drop(event)"></div> <div id="div 2" class="abox" style="background-color: #c 0 c 0 c 0; "></div> <div id="div 3" class="abox" style="background-color: #c 0 c 0 c 0; "></div> <p style="clear: both; margin-bottom: 2 px; "> <img id="drag 1" src="http: //www. w 3 schools. com/html/img_logo. gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </p> 1 -25
Drag & drop functions in order • By default, elements don’t allow things to be dropped on them • To allow a drop, the ondragover handler for the receiving object calls ev. prevent. Default() • We set the handler for the ondragstart event to define what data will be passed when we make the drop, in this case the id of the dragged object (the id of the ‘target’ of the drag event) • ev. data. Transfer. set. Data("Text", ev. target. id) • The ondrop handler of the receiving object is set to: ev. prevent. Default(); var data=ev. data. Transfer. get. Data("Text"); ev. target. append. Child(document. get. Element. By. Id(data)); • This prevents default behaviour; gets out the data that we transferred into the event ondragstart (the id of the dragged image); and appends the identified object into the target of the drop http: //www. w 3 schools. com/jsref/met_node_appendchild. asp 1 -26
Creating action with CSS • Can use ‘transition’ to specify a change in a property should unfold over a period of time Here we say that when the background changes, it takes 2 seconds Here we say that on hover (mouse cursor on the division) the background goes to a bluish-grey Can get a more subtle effect by making this something like 200 ms <html> <style> div. first { width: 80 px; border: solid 1 px black; transition: background 2 s; } div. first: hover{ background: #A 0 A 0 FF; }. . . </style> <body> <div class="first">Please hover here</div> Takes 2 s to turn blue-grey, and 2 s to turn back to white when mouse moves off 1 -27
Flying objects • Can create a named animation [this one’s called ‘mysecond’ since I apply it to anything of class = “second”] • Transitions any numeric properties (e. g. position, size, even colour) from one value to another over the specified time Have to specify it two ways as many popular browser brands haven’t caught up with the standard <html> <style>. second { position: absolute; -webkit-animation: mysecond 5 s; /* Chrome, Safari, Opera */ animation: mysecond 5 s; Set the normal left: 200 px; values identical to width: 500 px; the ‘to’ state of } @-webkit-keyframes mysecond the animation { from {left: 10 px; width: 50 px; } to {left: 200 px; width: 500 px; } } @keyframes mysecond { from {left: 10 px; width: 50 px; } to {left: 200 px; width: 500 px; } }. . . </style> <body> <img class="second" src="funny. X. png" alt="A funny X"> 28
Animation options • Many other CSS animation capabilities are available – see http: //www. w 3 schools. com/css 3_animations. asp • You can specify • Multiple destinations for the animation as percentages of the total journey /* Chrome, Safari, Opera */ • A number of repeats @-webkit-keyframes myfirst { 0% {background: red; left: 0 px; top: 0 px; } (including infinite) 25% {background: yellow; left: 200 px; top: 0 px; } 50% {background: blue; left: 200 px; top: 200 px; } • A delay before the 75% {background: green; left: 0 px; top: 200 px; } animation begins 100% {background: red; left: 0 px; top: 0 px; } } This animation moves the class to which it’s applied along a square route and through bold colours /* Standard syntax */ @keyframes myfirst { 0% {background: red; left: 0 px; top: 0 px; } 25% {background: yellow; left: 200 px; top: 0 px; } 50% {background: blue; left: 200 px; top: 200 px; } 75% {background: green; left: 0 px; top: 200 px; } 100% {background: red; left: 0 px; top: 0 px; } } 1 -29
A little bit 3 -D • Use the z-index attribute to set the priority of an object for overlapping others 1 -30 http: //www. w 3 schools. com/cssref/pr_pos_z-index. asp
Summary • You can use DHTML methods to make sophisticated interaction on web pages • HTML 5 is making these methods increasingly well standardised • P. S. Have fun, but remember to focus on creating a good user experience! 31
- Slides: 31