1 / 31

HTML5

Jim Warren (content based largely in W3C sources). HTML5. Learning outcomes. Describe and apply the capabilities considered ‘DHTML’ using HTML5 approaches Understand the Document Object Model (DOM) for Web pages Be able to write Javascript functions

ninon
Download Presentation

HTML5

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. Jim Warren (content based largely in W3C sources) HTML5

  2. Learning outcomes • Describe and apply the capabilities considered ‘DHTML’ using HTML5 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

  3. What is DHTML? • Dynamic HTML • It’s not a language • 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

  4. What is HTML5? • Subsumes HTML 4, XHTML 1 and DOM Level 2 HTML • Better handling for multimedia and graphical content to avoid resorting to proprietary plug-ins • <video>, <audio> and <canvas> elements • Scalable vector graphics (SVG) • MathML • Offers various APIs including drag-and-drop and Web storage (although technically the latter is now outside HTML5) • Even defines some processing for invalid documents for greater uniformity in responses to syntax errors • ‘Candidate recommendation’ of W3C as of Dec 2012 • But already widely supported and expected to be a ‘Recommendation’ in 2014 the human 1

  5. 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

  6. The Document Object Model (DOM) • The HTML DOM is a standard object model and programming interface for HTML. It defines: • 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 usingJavascript the human 1 http://www.w3schools.com/js/js_htmldom.asp

  7. Javascript • Javascript is a scripting language very broadly supported in browsers • Not really officially, or syntactically, all that related to Java: was officially called LiveScript 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

  8. 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 qualityassurance, but easy • alert pops up a dialog • .write (a method ofthe DOM documentobject) tacks contentonto the end of theHTML <html> <body> <h1>Javascript-generated output below</h1> <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>

  9. 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) • When the Javascriptis run, we use thedocument’s methodgetElementByIdto reference an elementby name (id) and thenaccess its contentsthrough its innerHTMLproperty <html><body><p id="intro">Hello World!</p><script>var txt=document.getElementById("intro"). innerHTML; document.write("\""+txt+"\"");</script></body></html> Using \ escape character to put a double-quote in double-quotes. So this line simply adds “Hello World!” (include quotes) at the bottom of the page

  10. Form validation • HTML5 gives you convenient types for 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:FF0000;} input:required:valid { border-color:00FF00;} </style> <h1>HTML5 forms</h1> <form> Your Name: <input type="text" name="name" required><br> Email Address: <input type="email" name="email" required placeholder="Enter a valid email address"><br> Website: <input type="url" name="website" required pattern="https?://.+"><br> Age: <input type="number" size="6" name="age" min="18" max="99" value="21"><br> Satisfaction: <input type="range" size="2" name="satisfaction" min="1" max="5" value="3"> <input type="submit" value="Submit" /> </form> Appearance in Chrome

  11. 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;base64,iVBO -- // ... // -- QmCC');          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 v13, but never mind]

  12. Another form control • Radio buttons • Multiple input controls all relating to the same form variable <label>Size:</label> <input type = "radio" name = "radSize" id = "sizeSmall" value = "small" checked = "checked" /> <label for = "sizeSmall">small</label> <input type = "radio" name = "radSize" id = "sizeMed" value = "medium" /> <label for = "sizeMed">medium</label> <input type = "radio" name = "radSize" id = "sizeLarge" value = "large" /> <label for = "sizeLarge">large</label> Note use of label controlsto be more explicit thatthe content serves ascaptions • In this case we set the value of radSize to “small”, “medium” or “large”

  13. 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) <head> <script> function show_data(element) { form=element.form; /* the button's form */ txt=form.elements.namedItem("name").value; alert("The name is: "+txt); } </script> </head> ... <input type="submit" onclick="show_data(this)" value="Submit button"> </form> Here we pull out the value of an input field (the one with name=“name”) from the form

  14. 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 thevalues on theinput controls • And there are otherevents than onclick • E.g. onmouseover,onmouseout • See http://www.w3schools.com/js/tryit.asp?filename=tryjs_events_mouseover <head> <script> function show_data() { form=document.getElementById("myform"); txt=form.elements.namedItem("name").value; alert("The name is: "+txt); } </script> </head> ... <form id="myform"> ... </form> <button onclick="show_data()">A button</button>

  15. 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>

  16. Dynamically changing your page through the DOM • Simply change the innerHTML 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 + "!<br><br> How are you today?"; document.getElementById("demo").innerHTML=x;} </script> Any piece of the HTML that you can get a handle on, you can change to something else!

  17. Dynamically changing visibility <script> function show_data() { form=document.getElementById("myform"); txt=form.elements.namedItem("vis").value; document.getElementById("demo").style.visibility=txt; } </script> </head> ... <form id="myform"> <label>Visibility:</label> <input type = "radio" name = "vis“ id = "visYes" value = "visible" onchange="show_data();"/> <label for = "visYes">Yes</label> <input type = "radio" name = "vis“ id = "visNo" value = "hidden" checked = "checked" onchange="show_data();"/> <label for = "visNo">No</label> ... <div id="demo" style="visibility:hidden">Boo!</div> • Visibility is a handy property for achieving interactive effects Setting the form variable visto actual value needed for DOM visibility property Using onchange event for immediate response • Even hidden elements get allocated space; also consider the display property http://www.w3schools.com/jsref/prop_style_display.asp

  18. 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 (1st parameter of window.open) or just write into its DOM to create it dynamically 3rd parameter is window ‘specs’ including what controls to enable <script> var myWindow = window.open("","MsgWindow","width=200,height=100"); myWindow.document.write("<title>Child</title>"); myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>"); myWindow.document.write("<button onclick=\"window.close();\">Close</button>"); </script> http://www.w3schools.com/jsref/met_win_open.asp

  19. Embedding data in a Web page • User-defined attributes • HTML5 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.getElementById('strawberry-plant'); var fruitCount = parseInt(plant.getAttribute('data-fruit'))-1; plant.setAttribute('data-fruit',fruitCount.toString()); // Pesky birds Note use of toString and parseInt(or whatever you need, egparseFloat) to move in and out of text

  20. Arrays of data from DOM • If you want to get multiple elements at a time you might like getElementsbyName <div id='strawberry-plant1' name="plant" data-fruit='12'></div> <div id='strawberry-plant2' name="plant" data-fruit='8'></div> <div id='blackberry-plant1' name="plant" data-fruit='25'></div> ... var plants=document.getElementsByName("plant"); alert(plants.length); alert(plants[2].getAttribute('data-fruit')); Returns an array 3 25

  21. Getting data back from a child window • Use window.opener in the childwindow to reference its parent <title>Parent Window</title> </head><body> <p id="intro">Hello World!</p> <script> var myWindow = window.open("","MsgWindow","width=300,height=200"); txt="<head><title>Child</title>"; txt+="\<script\>function sender() {"; txt+="dest=window.opener.document.getElementById(\"intro\");"; txt+="dest.innerHTML=document.getElementsByName(\"msg\")[0].value;"; txt+="window.close();}"; txt+="\</script\></head>"; txt+="<p>This is 'MsgWindow'. I am 300px wide and 200px tall!</p>"; txt+="Type a message: <input type=\"text\" name=\"msg\"><br><br>"; txt+="<button onclick=\"sender()\">Close</button>"; myWindow.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

  22. Web Storage • HTML5 Web Storage provides two new objects for storing data on the client • window.localStorage - stores data with no expiration date • code.sessionStorage - stores data for one session (data is lost when the tab is closed) • Faster and larger data limit than old method, ‘cookies’ • http://www.w3schools.com/html/html5_webstorage.asp 22

  23. Web Storage example • sessionStorage has setItem and getItem 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?"); sessionStorage.setItem("name_store",JSON.stringify(names)); ... // Retrieve value (persists until tab is closed) var div2 = document.getElementById("div2"); var retr_names = []; /*retr_names[1]="bob";*/ retr_names=JSON.parse(sessionStorage.getItem("name_store")); /*alert(retr_names[1]); */ div2.innerHTML="Name 1: "+retr_names[0]+"<br>Name 2: "+retr_names[1]; Note these JSON helper methods to push an array in and out of a string Sets the content of the element with id=div2 to the two interactively input names

  24. Drag & drop • A key feature of ‘direct manipulation’ interfaces popularised by the Macintosh • Part of HTML5 standard; to use it, define: • Something as draggable • What data to pick up for drag • What can receive a drop • How to process the drop http://www.w3schools.com/html/html5_draganddrop.asp

  25. Drap & drop code <style type="text/css"> div.abox {float:left;width:250px;height:70px;padding:10px;border:2px solid #aaaaaa;margin:5px} </style> <script> function allowDrop(ev) {ev.preventDefault();} function drag(ev) {ev.dataTransfer.setData("Text",ev.target.id);} function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </head><body> <p>Drag the W3Schools image into the rectangle:</p> <div id="div1" class="abox" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="div2" class="abox" style="background-color:#c0c0c0;"></div> <div id="div3" class="abox" style="background-color:#c0c0c0;"></div> <p style="clear:both;margin-bottom:2px;"> <img id="drag1" src="http://www.w3schools.com/html/img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </p> Define a style for a class of div called ‘abox’ Define event handlers Make 3 boxes, the first set to receive a drop, the others grey; define a draggable image

  26. 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.preventDefault() • 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.dataTransfer.setData("Text",ev.target.id) • The ondrop handler of the receiving object is set to: ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(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.w3schools.com/jsref/met_node_appendchild.asp

  27. Creating action with CSS • Can use ‘transition’ to specify a change in a property should unfold over a period of time Can get a more subtle effect by making this something like 200ms Here we say that when the background changes, it takes 2 seconds <html> <style> div.first { width: 80px; border: solid 1px black; transition:background 2s; } div.first:hover{ background:#A0A0FF; } ... </style> <body> <div class="first">Please hover here</div> Here we say that on hover (mouse cursor on the division) the background goes to a bluish-grey Takes 2s to turn blue-grey, and 2s to turn back to white when mouse moves off

  28. Flying objects 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 5s; /* Chrome, Safari, Opera */ animation: mysecond 5s; left:200px; width:500px; } @-webkit-keyframes mysecond { from {left:10px;width:50px;} to {left:200px;width:500px;} } @keyframes mysecond { from {left:10px;width:50px;} to {left:200px;width:500px;} } ... </style> <body> <img class="second" src="funnyX.png" alt="A funny X"> • 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 Set the normal values identical to the ‘to’ state of the animation

  29. Animation options • Many other CSS animation capabilities are available – see http://www.w3schools.com/css/css3_animations.asp • You can specify • Multiple destinations for the animation as percentages of the total journey • A number of repeats(including infinite) • A delay before theanimation begins /* Chrome, Safari, Opera */@-webkit-keyframes myfirst{0%   {background: red; left:0px; top:0px;}25%  {background: yellow; left:200px; top:0px;}50%  {background: blue; left:200px; top:200px;}75%  {background: green; left:0px; top:200px;}100% {background: red; left:0px; top:0px;}}/* Standard syntax */@keyframes myfirst{0%   {background: red; left:0px; top:0px;}25%  {background: yellow; left:200px; top:0px;}50%  {background: blue; left:200px; top:200px;}75%  {background: green; left:0px; top:200px;}100% {background: red; left:0px; top:0px;}} This animation moves the class to which it’s applied along a square route and through bold colours

  30. A little bit 3-D • Use the z-index attribute to set the priority of an object for overlapping others http://www.w3schools.com/cssref/pr_pos_z-index.asp

  31. Summary • You can use DHTML methods to make sophisticated interaction on web pages • HTML5 is making these methods increasingly well standardised • P.S. Have fun, but remember to focus on creating a good user experience!

More Related