HTML5/CSS3/JavaScript Programming( ) 1
/ meteorstartup@gmail.com Meteor Startup (http://meteorstartup.com) / / DB (with Meteor.js) 2
KT DataSystem OS X/iOS Meteor.js Getting Started RHCSA / RHCE 3
1. 1 2. 2 HTML5 3. 3 JavaScript jquery 4. 4 HTML5 API 5. 5 HTML5 6. 6 Extend Javascript 4
HTML5? HTML 2.0 (IETF) ~ HTML 4 (W3C) HTML 5 (WHATWG) HTML 5
HTML? 6
HTML5 7
? WEB 8
1 9
1. Web Architecture & Client/Server 2. Web Programming 3. 10
Web Architecture & Client/Server ( :,,,, ) ( : IIS, Apache, Apache Tomcat ) HTTP (WAS : Web Application Server) (C, JAVA, C#, ASP, JSP, PHP ) (DBMS), 11
Web Architecture & Client/Server CGI. Client request reresponse Server (CGI) CGI. 12
Web Architecture & Client/Server Server Client request reresponse ( ) Web Architecture. User Interface Developer Tool EAI Web Server Web Application Server e-business Solution DBMS Security/Auth 13
Web Architecture & Client/Server Web Architecture 1-Tier Client System A Http Server Application Server Database 2-Tier WAS DBMS Client System A System B Http Server Application Server JDBC Database 14
Web Architecture & Client/Server 3-Tier, WAS, DBMS Client System A System B System C Http Server Application Server JDBC Database 3-Tier 3-Tier System A System C Client Http Server Application Server JDBC System E Load Balancer System B Load Balancer System D Database Http Server Application Server JDBC 15
Web Architecture & Client/Server HTTP (Hyper Text) HTTP,,, URL,, ( ) (Header) [ / ] ( ) (Header) [ / ] (Body) [ ] (Body) [ ] - HTTP - - HTTP - 16
Web Architecture & Client/Server Http (Request) HTTP method(get/post), URL, (form) GET URL 256 (Body) POST ( ) GET /home/form.jsp?irum=hong&email=hong@daum. net HTTP/1.1 Host : www.example.com User-Agent : Mozilla/5.0. POST (Body) GET ( ) (Body) POST /home/form.jsp HTTP/1.1 Host : www.example.com User-Agent : Mozilla/5.0. irum=hong&email=hong@daum. net. 17
Web Architecture & Client/Server HTTP (Response) ( : HTTP 200(OK), 404(Not Found), 500(Internal Server Error) ) ( : text/html), ( ) (Body) HTTP/1.1 200 OK Server : Apache-Coyote/1.1 Content-Type : text/html;charset=utf-8.. 18
Web Programming? (Client)/ (Server) HTML (HTML, CSS, Javascript ) (Request) Html Code (Response) Html code - / - 19
Web Programming HTML(HyperText Markup Language) CGI(Common Gateway Interface) Common Gateway Interface CGI C, Perl DB (, MDB ) ASP(Active Server Page) Visual Basic VBScript IIS(Internet Information Server) PHP(Personal Hypertext Preprocessor) C, 20
Web Programming JSP (Servlet) JSP (JavaBeans), EJB JSTL 21
WebStorm: https://www.jetbrains.com/webstorm/ download/ (Windows) https://git-scm.com/download/win (64bit Git for Windows) https://www.meteor.com/install (On Windows)». ( Default Next ) 22
JDK Apache Tomcat Eclipse JDK - http://www.oracle.com/technetwork/java/index.html Apache Tomcat - http://tomcat.apache.org/ Eclipse - http://www.eclipse.org/ Eclipse Apache Tomcat 23
JDK 1. (jdk-8u20-windows-i586.exe) : http://www.oracle.com/technetwork/java/index.html 24
JDK 25
JDK 26
1. Tomcat 8.0 : http://tomcat.apache.org/ 27
1. Tomcat 8.0 windows Core 32bit/64bit Windows Service Installer. 28
1. : http://www.eclipse.org/ 29
Eclipse IDE for Java EE Developers 30
31
2 Web HTML5 32
1. Web 2. HTML5 3. HTML5 4. <video>, <audio> 5. Web Form 6. contenteditable 33
Web "." - (www ) - 34
Web Web, W3C,. HTML CSS. 3,,. 35
Web Web [Web,.] 36
HTML5 HTML5 HTML5 W3C( ) HTML WG(Working Group).,, API. / TV. HTML5 X(Active-X), (flash) (Silverlight), FX(JAVA FX) (web browser). 37
HTML5 HTML5 Web Hypertext Application Technology Working Group(WHATWG): Apple, Mozillar, Opera HTML. 38
HTML5 HTML5 HTML CSS, JavaScript API DOCTYPE (charset) DOCTYPE <!DOCTYPE html> <meta http-equiv="content-type" content="text/html; charset=utf-8">, <meta charset= utf-8 > HTML. text HTML5 email, tel, uri, datetime,. Canvas, SVG, WebGL 2D/3D CSS3 UI 39
HTML5 HTML5 HTML5 HTML ( ) CSS3 JavaScript. 40
HTML5 HTML5 Active-X HTML5 API Web. 41
HTML5 HTML5 HTML5 5. 42
HTML5 HTML5 (Semantic Markup) HTML5 section h1~h6 article aside hgroup header, footer nav audio, video 43
HTML5 canvas. API. mark datalist. charset : meta autofocus : input(type hidden ), select, textarea, button placeholder : input, textarea. required : input(type hidden, image, submit ), textarea 44
HTML5 autocomplete : input min, max : input pattern : input ( ) step : input novalidate : form label : menu menifest : html menifest 45
HTML5 HTML5 DOCTYPE <!DOCTYPE html> <header>, <body>,<section>,<article> 46
HTML5 <nav>,, <header>,<aside>,<footer> <article>,, <section> <article> <section> (<h1>~<h6> ) <section> <section> <aside>,, <section>,<article> <footer> ( ), 47
HTML5 <div> <div> id class <div> ( ) <!-- --> <body> <div id="header">... </div> <div id="nav">... </div> <div id="sidebar">... </div> <div id="section1">... <div id="article">... </div> </div> <div id="section2">... <div id="section2_1">... </div> </div> <div id="footer">... </div> </body> <!-- --> <body> <header>... </header> <nav>... </nav> <aside>... </aside> <section id="section1">... </article>... </article> </section> <section id="section2">... <section id="section2_1">... </section> </section> <footer>... </footer> </body> 48
<video>, <audio> MPEG4(*.mp4. *.m4v),,.mp4.m4v MPEG-4 part14 H.264 part10 AVC (*.flv) Ogg(*.ogv) Xiph.org (Ogg Theora) AVI(*.avi) WebM(*.webm) 2010 I/O VP8 Vobis. 49
<video>, <audio>, Chrome 10.0 ogg/theora, WebM, H.264* ogg/vorbis, mp3, wav, AAC Internet Explorer 9 H.264, WebM** mp3, AAC 10 H.264 mp3, AAC Safari 3 H.264 mp3, wav, AAC Opera 10.5 ogg/theora ogg/theora 11.1 ogg/theora, WebM ogg/theora, WebM Firefox 3.6 ogg/theora ogg/vorbis, wav 4 ogg/theora, WebM, H.264* ogg/vorbis, wav 50
<video>, <audio> <video> src poster preload autoplay loop controls width height 51
<video>, <audio> : play_video.html 52
<video>, <audio> (chap 2-1) [ HTML ] <header> <h1>html5 </h1> </header> <section id="player"> <video id="media" width="600" height="400" preload controls loop poster="poster.jpg"> <source src="trailer.mp4"> <source src="trailer.ogg"> </video> </section> [ CSS ] section, h1 { text-align : center; h1 { background-image : linear-gradient(to right, red, #f06d06, rgb(255, 255, 0), green); border-radius : 6px; text-shadow : 4px 4px 4px #ffffff; width : 80%; height : 80px; margin : auto; padding-top : 20px; font-size : 2.2em; header { margin-top : 10px; 53
(chapter2-2) <input> <input type= email > <input type= url > <input type= number > min :, max, :, step :, value : <input type= range > min :, max, :, step :, value :. <input type= search > x 54
<input type= date >, <input type= month >, <input type= week >, <input type= time > <input type= color > 55
<input> autocomplete : on autofocus min, max, step <input> date, month, week, time, number, range placeholder <input>. required multiple file <input>. 56
: book_rental.html 57
(chapter2-3) [ HTML ] <fieldset> <legend> </legend> <form method="get" action="..."> : <input type="text" name="p_name" required autofocus /> <br> : <input type="tel" name="p_tel" placeholder="00*-000*-0000" required pattern="[0-9]{2,3-[0-9]{3,4-[0-9]{4" /> <br> : <input type="email" name="p_mail" required placeholder="***@***.***"/><br> : <input type="text" size="40" name="book_title" /><br> : <input type="range" value="1" min="1" max="3" name="amount" onchange="updaterange(this);"/> <output id="rangevalue">1 </output><br> : <input type='date' name='p_date'><br> : <input type="time" name="time_from" min="09:00" max="18:00" > <input type="time" name="time_until" min="09:00" max="18:00" > <br> <hr> <input type="submit" value=" "/> </form> </fieldset> 58
[ JavaScript ] function updaterange(obj) { document.getelementbyid('rangevalue').innerhtml = obj.value + ' '; window.onload = function() { var domobj = document.queryselector("input[type=date]"); var d = new Date(); var year = d.getfullyear(); var month = d.getmonth()+1; var date = d.getdate(); if (month <= 9) month = "0"+month; if (date <= 9) date = "0"+date; var datestr = year+"-"+month+"-"+date; domobj.min = datestr; 59
contenteditable contenteditable (Element). true : false : inherit :., ( ) (contenteditable.html) 60
(chapter2-4) [ HTML ] <style>.edit_content { width : 500px; height : 200px; margin : 5px auto; padding : 10px; border : 1px dashed red;.edit_content[contenteditable=true] { border : 5px inset blue; background-color : skyblue; button { margin : 5px; </style> <h2>contenteditable </h2> <div class="edit_content"> contenteditable. </div> <button id="edit_btn" onclick="edit_content()"> </button> <button id="finish_btn" onclick="finish_content()"> </button> <button id="show_btn" onclick="show_content()"> </button> <script> var edittarget = document.queryselector(".edit_content"); function edit_content() { edittarget.setattribute("contenteditable", true); function finish_content() { edittarget.setattribute("contenteditable", false); function show_content() { alert(edittarget.textcontent); </script> 61
Cascade Style Sheet CSS(Cascading Style Sheets)? (HTML,XML) Style(,, ) (Language). CSS HTML CSS CSS. W3C HTML CSS. 62
Cascade Style Sheet CSS - HTML style - <style> - (.css) HTML [ CSS ] - (selector) - (property), ({ ) 63
Cascade Style Sheet CSS : : :, HTML :, CSS CSS1 - CSS W3C CSS1. - 1996 12. CSS2 - W3C 1998 5. CSS3-2005 12 5. -. - CSS3,,.. - CSS3.. 64
Cascade Style Sheet CSS3 CSS2 CSS3 CSS3. CSS. CSS3 text, fonts, color, backgrounds & borders, transforms, transitions, animations. CSS3 CSS2 JavaScript.,,,,,,. CSS3. [ CSS3 ] - - - - -,, - 65
Cascade Style Sheet CSS3 CSS3. CSS3. 66
67
3 JavaScript jquery 68
1. JavaScript 2. JavaScript 3. JavaScript 4. JavaScript 5. JavaScript 6. JavaScript 69
7. JavaScript 8. JavaScript BOM 9. JavaScript DOM 10. JavaScript 11. jquery 12. jquery DOM 70
JavaScript JavaScript JavaScript (Brendan Eich) (Mocha), (LiveScript), JavaScript. JavaScript.. (Rich Content) AJAX(Asynchronous JavaScript + XML) JavaScript. HTML5 HTML5 API JavaScript JavaScript. 71
JavaScript [ JavaScript 1 ] (chapter3-1) <script> document.writeln("javascript "); window.alert("html5 "); document.writeln("css3 "); console.log('ajax '); document.writeln(this); </script> [ JavaScript 2 ] (chapter3-2) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>insert title here</title> <script> alert("one"); </script> </head> <body> <h1> START</h1> <script> alert("two"); </script> <h1> END</h1> </body> </html> 72
JavaScript JavaScript number, string, boolean, null undefined. : 100, 3.14 : " ", 'abc' : true, false 73
JavaScript [ JavaScript 1 ] (chapter3-3) <script> var v_test; window.alert(v_test); v_test = 100; window.alert(v_test + 200); v_test = "100"; window.alert(v_test + 200); </script> [ JavaScript 2 ] (chapter3-4) <script> document.writeln("100 : " + typeof 100); document.writeln("3.14 : " + typeof 3.14); document.writeln(" : " + typeof " "); document.writeln(" : " + typeof sum); document.writeln("true : " + typeof true); document.writeln("function() { : " + typeof function() { ); document.writeln("[1,2,3] : " + typeof [ 1, 2, 3 ]); document.writeln("new Object() : " + typeof new Object()); var result; document.writeln(" : " + typeof result); </script> 74
JavaScript JavaScript (+), (-), (*), (/), (%), (++,--), (-) + : str = "ABCD" +"1234"; ==> "ABCD1234" <,>,<=, <=, ==, ===,!=,!== AND (&&), OR ( ), NOT (!),? =, += -=, *=, /=, %= AND(&), OR( ), XOR(^), (<<,>>) typeof delete 75
JavaScript [ JavaScript ] (chapter3-5) <script> document.writeln(100 + 200); document.writeln("100"+200); document.writeln('100'+'200'); document.writeln(" : " + (100+200)); document.writeln(" : " + 100*200); document.writeln((true > false) + "<br>"); document.writeln((true == 1) + "<br>"); document.writeln((true === 1) + "<br>"); var result; document.writeln((result " ") +"<br>"); </script> 76
JavaScript JavaScript if, switch switch. for, while, do-while for in (for-each.) for in /. break, continue.. try catch finally. 77
JavaScript [ JavaScript ] (chapter3-6) <script> if(100 > 50) document.writeln("100 50 "); var number = 10; if(number % 2 == 0) document.writeln(number + " "); else document.writeln(number + " "); var name; while (true) { name = window.prompt(" ", "javascript"); if (name == 'javascript') { window.alert(' ^^'); else if (name == 'java') { window.alert(' ^^'); break; else if (name == 'c++') window.alert('c++ ^^'); else window.alert(???'); </script> 78
JavaScript JavaScript JavaScript -. -. -.. -.. - length. -. JavaScript 2. - (.) [ 1, 2, 3, 4, 5 ] - Array() new Array(10) 79
JavaScript var array_example1 = new Array( "hello", "world" ); var array_example2 = [ "hello", "world" ]; var array_example3 = []; array_example3.push( "5" ); array_example3.push( "7" ); array_example3[ 2 ] = "2"; array_example3[ 3 ] = "12"; join(del) var array_example4 = []; del array_example4.push( 0 ); // [ 0 ] array_example4.push( 2 ); // [ 0, 2 ] array_example4.push( 7 ); // [ 0, 2, 7 ] pop() array_example4.pop(); // [ 0, 2 ] var array_example5 = [ "world", "hello" ]; shift() // [ "hello", "world" ] array_example5.reverse(); var array_example7 = [ 3, 4, 6, 1 ]; array_example7.sort(); // 1, 3, 4, 6 concat(ary) slice(start [,end]) push(data) unshift(data, ) reverse() sort([fnc]) tostring() start end-1 ( ),, 80
JavaScript [ JavaScript 1 ] (chapter3-7) <pre> <script> var ary1 = [ ]; var ary2 = new Array( ); var ary3 = new Array(10); // new Array('A') var ary4 = new Array(10, 20, 30); var ary5 = [10]; var ary6 = [10, 20, 30]; document.writeln("ary1.length - " + ary1.length); document.writeln("ary2.length - " + ary2.length); document.writeln("ary3.length - " + ary3.length); document.writeln("ary4.length - " + ary4.length); document.writeln("ary5.length - " + ary5.length); document.writeln("ary6.length - " + ary6.length); </script> </pre> [ JavaScript 2 ] (chapter3-8) <script> var ary = [100, 200, 'javascript']; for(var i=0; i < ary.length; i++) document.write(ary[i] + " "); document.write("<br>"); for(var index in ary) document.write(ary[index] + " "); </script> 81
JavaScript [ JavaScript ] (chapter3-9) <pre> <script> var ary = [5, 25, 10]; //var ary = ["abc", "xyz", "b"]; document.writeln(ary.sort( )); document.writeln(ary.sort( function(x, y) { return x - y; )); document.writeln(ary.sort( function(x, y) { return y - x; )); </script> </pre> 82
JavaScript JavaScript (function). function myfunction([...[, ]]) { /* do something */ var myfunction = function([...[, ]]) { /* do something */ 83
JavaScript JavaScript [ 1 ] var msg = function( person, greeting ) { var text = greeting + ", " + person; alert( text ); ; msg(" ", "?" ); [ 2 ] var msg = function( person, greeting ) { var text = greeting + ", " + person; return text; ; alert(msg(" ", "?" )); [ 3 ] var myfn = function( fn ) { var result = fn(); console.log( result ); ; myfn( function() { return "hello world"; ); [ 4 ] var myfn = function( fn ) { var result = fn(); console.log( result ); ; var myotherfn = function() { return "hello world"; ; myfn( myotherfn ); 84
JavaScript [ JavaScript 1 ] <pre> <script> myfunc1(); //myfunc2(); function myfunc1( ) { document.writeln(" "); var myfunc2 = function ( ) { document.writeln(" ( ) "); myfunc1(); myfunc2(); </script> </pre> 85
JavaScript [ JavaScript ] <pre> <script> var triangle1 = new Function('base', 'height', 'return base * height / 2;'); document.writeln(' (Function ) ' + triangle1(5, 2)); var param = 'height, width'; var formula = 'return height * width / 2;'; var diamond = new Function(param, formula); document.writeln(' ' + diamond(5, 2)); var triangle2 = function(base, height) { return base * height / 2; ; document.writeln(' ( ) ' + triangle2(5, 2)); function triangle3(base, height) { return base * height / 2; document.writeln(' ( ) ' + triangle3(5,2)); </script> </pre> 86
JavaScript [ JavaScript ] <pre> <script> var g_v = " "; function myfunc1() { var l_v = "myfunc1() "; document.writeln("myfunc1() "); document.writeln("l_v : " + l_v); document.writeln("g_v : " + g_v); var myfunc2 = function () { var l_v = "myfunc2() "; document.writeln("myfunc2() "); document.writeln("l_v : " + l_v); document.writeln("g_v : " + g_v); myfunc1(); document.writeln(); myfunc2(); document.writeln(); document.writeln(" ( ) ");K document.writeln("g_v : " + g_v); document.writeln("l_v : " + l_v); </script> </pre> 87
JavaScript [ JavaScript 1 ] <script> function test() { document.writeln("<h1>"+arguments.length+"</h1>") var i; document.writeln("<ul>"); for(i=0;i < arguments.length; i++) document.writeln("<li>"+arguments[i]); document.writeln("</ul>"); test(); test(100); test(10, 20, 30); test(10, 20, 30, 40, 50, 60, 70, 80); </script> [ JavaScript 2 ] <script> try { showmessage('javascript', 'css3', 'html5'); catch (e) { alert(e); finally { console.log(' '); </script> 88
JavaScript [ JavaScript ] <h1> </h1> <hr> <button onclick="testparatype(100);"> </button> <button onclick="testparatype('test');"> </button> <button onclick="testparatype({ );"> </button> <button onclick="testparatype(function(){ );"> </button> <button onclick="testparatype();"> </button> <button onclick="testparatype(true);"> </button> <script> function testparatype(p) { if(typeof p == 'number') alert(' '); else if(typeof p == 'string') alert(' '); else if(typeof p == 'object') alert(' '); else if(typeof p == 'function') alert(' '); else if(typeof p == 'undefined') alert(' '); else alert('???'); </script> 89
JavaScript [ JavaScript 1 ] <script> function highorderfunction(p) { if (typeof p == 'function') { p(' '); else { alert(p); highorderfunction(function (msg) {document.write(msg);); highorderfunction(function (msg) {console.log(msg);); highorderfunction(); highorderfunction(' '); </script> [ JavaScript 2 ] <script> function outerfunction() { return function () { document.write('<h1>hello World..!</h1>'); ; outerfunction( )( ); var result = outerfunction( ); result( ); result( ); </script> 90
JavaScript JavaScript data(property) data Method. JavaScript Property prototype object. Method Property,... JavaScript Object. JavaScript. 91
JavaScript JavaScript JavaScript 2. - - { :, :, ( ). function ([ ]) { this. = ; this. = ; 92
JavaScript [ JavaScript 1 ] <script> var person = { name : ' ', eat : function(food) { alert(this.name + " " + food + "!!"); ; person.eat(" "); </script> [ JavaScript 2 ] <script> var obj = { name: ' ', age: 19, kind: ' ' ; var jsonstr = JSON.stringify(obj); alert(jsonstr); var copy = JSON.parse(jsonStr); alert(copy.name + '\n' + copy.age + '\n' + copy.kind); </script> 93
JavaScript JavaScript var person1 = new Object(); person1.firstname = "Ankita"; alert( person1.firstname ); var people = {; people[ "person1" ] = person1; alert( people[ "person1" ].firstname ); var person2 = { firstname: "Ankita", lastname: "Gupta" ; alert( person2.firstname + " " + person2.lastname ); function car (make, model, color) { this.make = make; this.model = model; this.color = color this.displaycar = displaycar; function displaycar() { document.writeln("make = " + this.make) mycar = new car ("Ford", "Focus", "Red"); mycar.displaycar(); mycar.make = "BMW"; mycar.displaycar(); 94
JavaScript [ JavaScript ] <script> function Student(name, korean, math, english, science) { // this.name = name; this.kor = korean; this.math = math; this.eng = english; this.sci = science; // this.getsum = function () { return this.kor + this.math + this.eng + this.sci; ; this.getaverage = function () { return this.getsum() / 4; ; this.tostring = function () { return this.name + ' ' + this.getsum() + ' ' + this.getaverage(); ; ; var students = [ ]; students.push(new Student(' 1', 87, 98, 88, 95)); students.push(new Student(' 2', 92, 98, 96, 98)); students.push(new Student(' 3', 76, 96, 94, 90)); students.push(new Student(' 4', 98, 92, 96, 92)); students.push(new Student(' 5', 95, 98, 98, 98)); students.push(new Student(' 6', 64, 88, 92, 92)); students.push(new Student(' 7', 82, 86, 98, 88)); students.push(new Student(' 8', 88, 74, 78, 92)); var output = ' \n'; for (var i in students) { output += students[i].tostring() + '\n'; alert(output); </script> 95
JavaScript JavaScript JavaScript. BOM Browser Object Model. Web. DOM Document Object Model. Web. window document Document. Document. 96
JavaScript (Standard Built-in Object) JavaScript.. JavaScript. Object : JavaScript. Function :. Array :. String : Wrapper. Boolean : Wrapper. Number : Wrapper. Math :. Date :. RegExp : ( ). 97
JavaScript BOM BOM - window :,, iframe - - navigator : (, ) - document : - location : URL - history : URL 98
JavaScript DOM DOM? (DOM; Document Object Model). DOM / W3C. W3C API. HTML DOM JavaScript DOM. document,body DOM HTML,,. 99
JavaScript DOM DOM DOM. [ ] DOM document. - document.getelementsbytagname(' ') DOM - document.getelementbyid ('id ') id DOM - document.getelementsbyclassname('class ') class DOM - document.queryselector(' Dom CSS ') DOM - document.queryselectorall(' Dom CSS ') DOM node.nodevalue. node.innerhtml. node.getattribute(' '). 100
JavaScript DOM DOM DOM /. DOM 2. - node.innerhtml node.innertext. - document.createxxx() DOM.. appendchild() : insertbefore() : replacechild() : remodechild() : clonenode() : node.setattribute(' ', ' ') node.removeattribute(' '). 101
JavaScript JavaScript JavaScript. Web ( ) ( ). - event. ' ', ' '. - event target. - event type. click. - event handler. JavaScript. load, click mousedown, mousemove, mouseover, mouseup keydown, keypress, keyup change, reset, submit blur, focus 102
JavaScript DOM - HTML. -. - DOM. -. - null. / DOM DOM. - addeventlistener(eventname, handler, usecapture) : - removeeventlistener(eventname, handler) : 103
JavaScript <script> function btn_onclick(){ window.alert(?'); </script> <input type="button" value=" " onclick="btn_onclick() > <script> window.onload = function() { document.getelementbyid('btn').onclick = function(){ window.alert('?'); ; ; </script> <input id="btn" type="button" value=" > <script> window.addeventlistener('load', function() { document.getelementbyid('btn').addeventlistener('click', function(){ window.alert('?');, false, false); </script> <input id="btn" type="button" value=" "> 104
JavaScript [ JavaScript ] <div id="main"> <p>..</p> <p onclick="alert('.!')">..</p> <p>..</p> </div> <script> function showalert(){ alert('.!'); function clickme(){ document.getelementsbytagname('p')[0].onclick=showalert; window.onload=clickme; </script> 105
JavaScript [ JavaScript ] <div id="main"> <p>javascript</p> <p>html5</p> </div> <p>css3</p> <script> function clickme() { var list = document.queryselectorall("div>p"); for (var i = 0; i < list.length; i++) { list[i].onclick = showalert; list[i].onmouseover = function() { this.style.color = 'red'; ; list[i].onmouseout = function() { this.style.color = 'black'; ; function showalert(e) { alert(e.type + "!! - " + e.target.innerhtml); window.onload = clickme; </script> 106
JavaScript [ JavaScript ] <input type="button" id='btn' value=" "> <script> function addlistener(elem, ev, listener) { if(elem.addeventlistener) { elem.addeventlistener(ev, listener, false); else if(elem.attachevent) { // IE 8 elem.attachevent('on' + ev, listener); else { throw new Error('.'); addlistener(window, 'load', init); function init() { addlistener(document.getelementbyid('btn'), 'click', function() { window.alert('.'); ); </script> 107
jquery jquery? HTML. (John Resig) 2006. jquery. [ ] - DOM. (Sizzle ) - DOM - CSS DOM - - - AJAX - JSON - 108
jquery jquery DOM,, AJAX, Core jquery( ) Selectors DOM CSS CSS Traversing DOM Manipulation DOM Attributes Events,, Effects Ajax Ajax UI 109
jquery jquery jquery <script>. <script src="http://code.jquery.com/jquery-xxx.js"></script> jquery. jquery( ).xxx() jquery.xxx() jquery() jquery( selector [, context ] ) jquery( element ) jquery( elementarray ) jquery( object ) jquery( selection ) jquery() jquery( html [, ownerdocument ] ) jquery( html, attributes ) jquery( callback ) jquery() $( ) 110
jquery $() jquery(document).ready(function() {..... ); $(document).ready(function() {..... ); $(function() {..... ); DOM - $( ) jquery DOM 'jquery ' - DOM 'jquery ' - DOM jquery jquery('div').html('<h1> </h1>') $('div').html('<h1> </h1>') 111
jquery $() 112
jquery $( ).css(css ) CSS $( ).css(css, CSS ) $( ).css({css ) $( ).addclass(css ) CSS ( ( {' ':' ', ' ':' ',... )) class (CSS ) $( ).removeclass(css ) class ( CSS ) $( ).toggleclass(css ) class, (CSS / ) $( ).hasclass(css ) $( ).width() $( ).width( ) $( ).height() $( ).height( ) class (CSS ) 113
jquery DOM DOM DOM (traversing) : DOM ( : ) $(), $( ).find( ) $( ).children( ) [ ] $( ).parent( ) $( ).parents( ) [ ] $( ).siblings( ) [ ] $( ).prev( ) [ ] $( ).prevall( ) [ ] $( ).next( ) [ ] $( ).nextall( ) [ ] 114
jquery DOM DOM (jquery ) ( 0 ) $( ).filter( ) $( ).slice( [, ]) $( ).first( ) $( ).last( ) $( ).eq(n) n $( ).has( ) $( ).is( ) 'true' $( ).not( ) 115
jquery DOM HTML5 jquery DOM $( ).append( ) $( ).prepend( ) $( ).after( ) $( ).before( ) $( ).empty( ) ( ) $( ).remove( ) ( ) $( ).replacewith( ) $( ).clone( ) $( ).wrap( ) ( ) $( ).unwrap( ) 116
jquery DOM jquery $( ).html( ) HTML5 ( ) $( ).html(html5 ) HTML5 $( ).text( ) $( ).text( ) $( ).size( ) $( ).length $( ).get( ) (0 ) $( ).index( ) ( ) $( ).each( ) 117
jquery DOM DOM DOM $( ).attr( ) $( ).attr(, ) $( ).attr({ ) $( ).attr(, ( )) ( ( { :, :,... )) $( ).removeattr( ) $( ).val( ) ( ) value $( ).val( ) ( ) value 118
jquery each( ) ( ) $( ) jquery jquery ( ) $(this) <ul> </ul> <li> </li><li> </li><li> </li><li> </li> $('li').each(function(){ alert($(this).text()); ); 119
jquery on() function clickeventfunc() { alert('hi'); $('div').click(clickeventfunc); $('div').on('click', clickeventfunc); off() $(' ').off(' ') ; $(' ').off() ; // // 120
jquery / jquery $( ).on( ) (jquery ) $( ).off( ) on() $( ).bind( ) (jquery ) $( ).unbind( ) bind() $( ).one( ) (jquery ) ( ) $( ).trigger( ) (jquery ) $( ).live( ), $( ).delegate( ) (jquery ) $( ).die( ), $( ).undelegate( ) live() 121
jquery $( ).click( ) $( ).hover( ) ( ) $( ).toggle( ) $( ).focus( ) $( ).blur( ) $( ).change( ) $( ).select( ) $( ).keydown( ) $( ).ready( ) $( ).load( ) $( ).unload( ) DOM 122
jquery. ( ) show([ms][,function( )) hide([ms][,function( )) toggle([ms][,function( )) slideup([ms][,function( )) slidedown([ms][,function( )) slidetoggle([ms][,function( )) fadein([ms][,function( )) fadeout([ms][,function( )) fadetoggle([ms][,function( )) show() hide() show( ) ; // (1) show(600) ; show('slow') ; // (2), show(200, function( ) {... ) ; // (3) 123
jquery animate( ) CSS3 animate([properties][,ms][,function( )) (properties) - CSS3 - CSS3, ) : 1/1000 slow, normal, fast animate(,, ) $('p').animate({font-size: "3em", 2000); // 3 $('div').animate({height: "25%", "slow"); // div 1/4 $('div:has(img)').animate({width: "0px", 1000); // div 124
125
4 HTML5 API 126
1. XMLHttpRequest API 2. Canvas API 3. Drag&Drop API 4. Multimedia API 5. File API 6. Web Storage AP 127
7. Indexed DB API 8. Web Messaging API 9. Server-Sent Events API 10. Web Socket API 11. Web Worker API 128
XMLHttpRequest API AJAX? Web Web. AJAX (refresh )., Web. 129
XMLHttpRequest API Web AJAX Web 130
XMLHttpRequest API..(refresh) AJAX.. 131
XMLHttpRequest API AJAX JavaScript. XMLHttpRequest.. XMLHttpRequest.. XMLHttpRequest Web. 132
XMLHttpRequest API XMLHttpRequest XMLHttpRequest. XMLHttpRequest JavaScript. XMLHttpRequest : new XMLHttpRequest() XMLHttpRequest onreadystatechange readystate HTTP status HTTP Status statustext HTTP Status responsetext plaintext responsexml XML(XMLDocument ) abort() getallresponseheaders() HTTP getresponseheader(header) HTTP open(... ) HTTP setrequestheader(header,value) send(body) HTTP ( body ) upload XMLHttpRequestUpload 133
XMLHttpRequest API status 200 OK( ) 401 Unauthorized( ) 403 Forbidden( ) 404 Not Found( ) 500 Internal Server Error( ) 503 Service Unavailable( ) readystate 0 - (open() ) 1 - (open, send ) 2 - (send, / ) 3 - ( /, ) 4-134
XMLHttpRequest API open() send() open(http, URL [, ]) - HTTP : (GET, POST, PUT, DELETE..) - URL : AJAX - : true( ), false( ) send([ ]) - POST Query - ArrayBufferView, Blob, Document, DOMString, FormData, null. XMLHttpRequest - onloadstart - onprogress - onabort - onerror - onload - ontimeout - onloadend - onreadystatechange 135
XMLHttpRequest API (server push)... AJAX Polling Long Polling (comet). 136
XMLHttpRequest API jquery AJAX jquery Ajax. jquery Mobile Ajax. AJAX jquery Ajax $.ajax( ) $.get( ) $.post( ) / Ajax ) $.ajax({ url: 'service.php', success: function(data) { $('#area').html(data); ); GET ajax( ) ) $.get('sample.html', function(data) { $('#area').html(data); ); POST ajax( ) ) $.post('sample.html', function(data) { $('#area').html(data); ); 137
XMLHttpRequest API $.getjson( ) load( ) $.getscript( ) $.ajaxsetup( ) ajaxstart( ) ajaxstop( ) JSON ajax( ) ) $.getjson('sample.json', function(data) { $('#area').html('<p>' + data.age + '</p>'); ); HTML ) $('#area').load('sample.html', function( ) { ; ); ajax( ) ) $.getscript('sample.js', function( ) { ; ); ajax( ) ) $.ajaxsetup({ url: 'service.php' ); Ajax ) $('#img1').ajaxstart(function( ){ $(this).show(); ); Ajax ) $('#img1').ajaxstop(function( ){ $(this).fadeout(2000); ); 138
XMLHttpRequest API ajaxsend( ) ajaxsuccess( ) ajaxerror( ) ajaxcomplete( ) Ajax ) $("#msg").ajaxsend(function(event, request, settings){ $(this).append("<p>" + settings.url + " </p>"); ); Ajax ) $("#msg").ajaxsuccess(function(event, request, settings){ $(this).append("<p> </p>"); ); Ajax ) $("#msg").ajaxerror(function(event, request, settings){ $(this).append("<p>" + settings.url + " </p>"); ); Ajax ( / ) ) $("#msg").ajaxcomplete(function(event,request, settings){ $(this).append("<p> </p>"); ); 139
XMLHttpRequest API $.ajax( ) Ajax Ajax Ajax $.ajax() : $.ajax( url [, settings ] ) settings : JavaScript : url : URL type : data : timeout : datatype : Async : success : function(data) error : function( ) ( ) URL (, : ) ) "sample.php", "sample.html", "sample.xml" HTTP ) "get"( ), "post" ( ) ( ) ) 20000 ( ) ) "xml", "html", "json", "jsonp", "script", "text" ( : true) (data: ) 140
XMLHttpRequest API $.getjson( ) GET JSON $.getjson( url [, data ] [, success ] ) url data success(data) ( ) URL (, : ) ) "sample.json" ( ) (data: ) $.load( ).load( url [, data ] [, complete ] ) url data success(data) ( ) URL (, : ) ) "sample.html" ( ) (data: ) 141
XMLHttpRequest API AJAX Same Origin Policy(SOP) (Resource). SOP - Open API Open API In-House Open API - RIA OpenAPI ( ) file:// 142
XMLHttpRequest API AJAX SOP 1 Client Origin. ( ) Origin [ ] Proxy Origin (file://) 143
XMLHttpRequest API AJAX SOP 2 JSONP Cross Origin (file://) Client API AJAX [ ] GET Script 144
XMLHttpRequest API [ ] <html> <script> function parseresponse(data) { </script> <body> <script type="application/javascript" src="http:// /xxx/yyy?jsonp=parseresponse"> </script> [ Server ( ) ] parseresponse({ "Name": "Foo", "Id": 1234, "Rank": 7 ); [ ] <script type="text/javascript"> function datahandler(objdata) { console.log(objdata.one); ; </script> <script src="http:// /xxx/datap.json"> </script> [ Server ( ) ] datahandler( { one: "Singular sensation", two: "Beady little eyes", three: "Little birds pitch by my doorstep ); 145
XMLHttpRequest API jquery JSONP $.getjson("http:// /server/data.jsp?callback=?", function(d) { );. $.ajax({ url : "http:// /xxx/data.jsp", datatype : "jsonp ", jsonp : "callback", success : function(d){ ); $('a').click(function() { $.ajax({ url: "http:// /jsonp.json", ); ); datatype: 'jsonp', jsonpcallback: "mycallback", success: function(data) { console.log(' - ', data);, error: function(xhr) { console.log(' - ', xhr); function datahandler(objdata) { console.log(objdata.one); ; $(function() { $.ajax({ type: 'GET', url: 'http:// /xxx/datap.json', async: true, jsonpcallback: 'datahandler', contenttype: "application/json", datatype: 'jsonp', success: function(objdata) { console.log(objdata.one);, error: function(e) { console.log(e.message); ); ); 146
XMLHttpRequest API [ AJAX XML JavaScript ] var request = new XMLHttpRequest(); request.onreadystatechange = function (event) { alert('readystate : ' + request.readystate +' HTTP : ' + + request.status); if (request.readystate == 4) { if (request.status == 200) { var xml = request.responsexml; var roote = xml.getelementsbytagname('testxml'); var output = ''; for(var i=1; i < roote[0].childnodes.length; i+=2) output += "<h1>"+roote[0].childnodes[i].firstchild.nodevalue+"</h1>"; document.body.innerhtml += output; ; request.open('get', 'content/testxml.xml', true); request.send(); [ XML ] <?xml version="1.0" encoding="utf-8"?> <testxml> <name> </name> <age>19</age> <kind> OOP </kind> </testxml> 147
XMLHttpRequest API [ AJAX JSON JavaScript ] var request = new XMLHttpRequest(); request.onreadystatechange = function (event) { if (request.readystate == 4) { if (request.status == 200) { var str = request.responsetext; alert(str); var result = JSON.parse(str); var output = ""; for(var i in result) output += "<h1>" + result[i] +'</h1>'; document.body.innerhtml += output; ; request.open('get', 'content/testjson.txt', true); request.send(); [ JSON ] { "name" : " ","age" : 19,"kind" : " OOP " 148
XMLHttpRequest API [ AJAX XML jquery ] $.ajax('content/testxml.xml', { success : function(data) { alert(data); $(data).find('testxml').each(function() { $('body').append("<h1>name : " + $(this).find('name').text() + '</h1>'); $('body').append("<h1>age : " + $(this).find('age').text() + '</h1>'); $('body').append("<h1>kind : " + $(this).find('kind').text() + '</h1>'); ); ); [ AJAX JSON jquery ] $.ajax('content/testjson.txt', { success : function(data) { var result = JSON.parse(data); $.each(result, function(key, value) { $('body').append("<h1>" +key+ " : " +value + '</h1>'); ); ); $.getjson('content/testjson.txt', function(data) { $.each(data, function(key, value) { $('body').append("<h1>" +key+ " : " +value + '</h1>'); ); ); 149
XMLHttpRequest API XMLHttpRequest Level 2( XHR 2) HTML5 AJAX - CORS (AJAX Cross Domain ) - AJAX (load, error, loadstart, progress...) -. responsetype : "", "arraybuffer", "blob", "document", "json", "text". response :. - FormData : multipart/form-data POST AJAX.. 150
XMLHttpRequest API [ FormData POST 1 ] <section id="formbox"> <form name="form"> <p><input type="button" name="button" id="button" value="ajax "></p> </form> </section> <section id="databox"></section> <script> function initiate(){ databox=document.getelementbyid('databox'); var button=document.getelementbyid('button'); button.addeventlistener('click', send, false); function send(){ var data=new FormData(); data.append('name','javascript'); data.append('age','19'); data.append('kind', "OOP Based Web Programming Language"); var url="test.jsp"; var request=new XMLHttpRequest(); request.addeventlistener('load',show,false); request.open("post", url, true); request.send(data); function show(e){ databox.innerhtml=e.target.responsetext; window.addeventlistener('load', initiate, false); </script> 151
XMLHttpRequest API [ FormData POST 2 ] <h1>ajax FormData </h1> <h2>...</h2> <form id="myform" action="test.jsp"> : <input type="text" name="name" required autofocus><br> : <input type="number" name="age" required><br> : <input type="text" name="kind" size="50" required><br> <input type="submit" onclick="return sendform(this.form);"> </form> <div id="result"></div> <script> function sendform(form) { var formdata = new FormData(form); formdata.append('secret_token', '1234567890'); var xhr = new XMLHttpRequest(); xhr.open('post', form.action, true); xhr.responsetype = 'text'; xhr.onload = function(e) { if (this.status == 200) { document.getelementbyid("result").innerhtml = "<h2> </h2>" + this.response; ; xhr.send(formdata); return false; </script> 152
XMLHttpRequest API [ FormData POST 3 ] <h1 onclick="getimage();">... AJAX...</h1> <script> function getimage() { var xhr = new XMLHttpRequest(); xhr.open('get', 'duke_luau.png', true); xhr.responsetype = 'blob'; xhr.onload = function(e) { if (this.status == 200) { var blob = this.response; var img = document.createelement('img'); img.width=200; img.height=200; img.onload = function(e) { window.url.revokeobjecturl(img.src); ; img.src = URL.createObjectURL(blob); document.body.appendchild(img); ; xhr.send(); </script> 153
XMLHttpRequest API [ FormData POST 4 ] <h1>html5 FormData </h1> <hr> <h2>.</h2> <form id="testform"> <input type="file" name="myuploadfile" multiple><br><br> <input type="button" id="uploadbutton" value=" " > </form> <script> function process() { var btn = document.queryselector("#uploadbutton"); btn.onclick = function() { var form = document.queryselector("#testform"); var xhr = new XMLHttpRequest(); var formdata = new FormData(form); xhr.open("post", "process.jsp", true); xhr.onload = function(oevent) { alert(" "); ; xhr.send(formdata); window.onload = process; </script> 154
XMLHttpRequest API Cross Origin Resource Sharing(CORS) Cross Domain.(, Origin ) Origin. Open API DB CORS. HTTP CORS.. response.addheader("access-control-allow-origin", "*"); [ Access-Control ] response.setheader("access-control-allow-methods", "POST, GET, OPTIONS, DELETE"); POST, GET, OPTIONS, DELETE. response.setheader("access-control-allow-headers", "x-requested-with");, AJAX jquery AJAX, (x-requested-with). response.setheader("access-control-allow-origin", "*"); * *. 155
Canvas API Canvas API? HTML5 API. <canvas>.,,,. <canvas> :. <canvas id= "draw" width= "400" height= "300"></canvas> HTMLCanvasObject <canvas> DOM. <canvas> (JavaScript ). var area = document.getelementbyid("draw"); var ctx = area.getcontext("2d"); ctx.fillstyle = "rgb(255,0,0)"; ctx.fillrect (10, 10, 100, 100); 156
Canvas API Canvas API SVG 157
Canvas API fillrect(x, y, width, height) :. strokerect(x, y, width, height) :. clearrect(x, y, width, height) :. beginpath() :. closepath() :. stroke() :. fill() :. moveto(x,y) : (x,y). lineto(x,y) : x y. stroketext(msg, x, y) : (x,y). filltext(msg, x, y) : (x,y). measuretext(msg) : TextMetrics. arc(x, y, r, startangle, endangle, anticlockwise) : (x,y) (anticlockwise) (r). 158
Canvas API quardraticcurveto(cp1x, cp1y, x, y) : (cp1x,cp1y) (x,y) beziercurveto(cp1x, cp1y, cp2x, cp2y, x, y) : (cp1x,cp1y) (cp2x,cp2y) (x,y). drawimage(image, sx, sy) drawimage(image, sx, sy, swidth, sheight) drawimage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight). 159
Canvas API : CanvasGradient. - createlineargradient(x1, y1, x2, y2) :. - createradialgradient(x1, y1, r1, x2, y2, r2) :. - CanvasGradient addcolorstop(position, color) : position(0.0~1.0) color. : CanvasPattern. - createpattern(image, type) : image type. image CanvasImageSource type repeat, repeat-x, repeat-y, no-repeat. save () strokestyle fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation restore(). 160
Canvas API [ ] fillstyle :, CanvasGradient, CanvasPattern. strokestyle :, CanvasGradient, CanvasPattern. globalalpha :. 0( ) 1( ) [ ] linewidth :, 1 linecap :. - butt : - round : 1/2 - square : linejoin :. - round : - bevel : - miter :.. 161
Canvas API shadowoffsetx x.( 0, ) shadowoffsety y.( 0, ) shadowblur :.( 0) shadowcolor :.. scale(x, y) :. rotate(angle) :. translate(x, y) :. globalcompositeoperatio : ( ) ( ). 162
Canvas API HTMLObjectCanvas - createimagedata(sw, sh) - createimagedata(imagedata ) (ImageData). - getimagedata(sx, sy, sw, sh) : <canvas> (ImageData). - putimagedata(imagedata, dx, dy) : <canvas> (dx, dy) (ImageData). HTMLObjectCanvas todataurl() : <canvas> png URI. var canvas = document.getelementbyid("draw"); var dataurl = canvas.todataurl(); console.log(dataurl); // "data:image/png;base64,ivborw0kggoaaaansuheugaaaauaaaafcayaaacnby // blaaaadeleqvqimwngobmaaabpaafei8araaaaaelftksuqmcc" 163
Canvas API : memo_canvas.html 164
Canvas API [ HTML ] <button onclick="setcolor('red');">red</button> <button onclick="setcolor('blue');">blue</button> <button onclick="setcolor('green');">green</button> <button onclick="setcolor('yellow');">yellow</button> <button onclick="setcolor('black');">black</button><br><br> <canvas id="mycanvas" width="580" height="450"></canvas> [ JavaScript ] function setcolor(color) { drawcolor = color; function initialize() { context.clearrect(0,0,580,450); context.beginpath(); context.rect(0,0,580,450); context.strokestyle = "silver"; context.fillstyle = "LightGoldenrodYellow"; context.fill(); context.linewidth = 0.5; for(i=1;i<=8;i++) { context.moveto(5,i*50); context.lineto(575, i*50); context.stroke(); 165
Canvas API function startdrawing() { drawing = true; context.beginpath(); context.strokestyle = drawcolor; context.linewidth = 1; context.arc(event.clientx - rect.left, event.clienty - rect.top, 3, 0, 2*Math.PI); context.stroke(); context.fillstyle = drawcolor; context.fill(); context.closepath(); context.beginpath(); context.moveto(event.clientx - rect.left, event.clienty - rect.top); context.linecap = "round"; context.linewidth = 6; function keepdrawing() { if (drawing) { var x,y; if (device == "mobiledevice") { x = event.targettouches[0].pagex; y = event.targettouches[0].pagey; else { x = event.clientx; y = event.clienty; context.lineto(x - rect.left, y - rect.top); context.stroke(); function stopdrawing() { if (drawing) { context.stroke(); drawing = false; 166
Drag & Drop API Drag & Drop API? API (drag source) (drop target) (data transfer) 167
Drag & Drop API dragstart drag. drag datatransfer. dragenter dropzone dragleave dropzone dragover dropzone drag. drop dragend drop.. 168
Drag & Drop API draggable dragable true. ) <div id= dragsource dragable= true > datatransfer datatransfer setdata(format, data) draggable dragstart draggable key/value MIME : text, URL : url getdata(format) droppable drop draggable MIME cleardata([format]).. 169
Drag & Drop API datatransfer types items files setdragimage(element, x, y).. (x, y). addelement(element). effectallowed none, copy, copylink, copymove, link, linkmove, move, all ( ). copy copy move link. dropeffect 170
Drag & Drop API MIME text/plain text MIME image/png png MIME image/jpg jpg MIME image/gif gif MIME dropzone. <div dropzone="copy s:text/plain s:text/html" ondrop= dropevent(event, this)"> dropzone copy, move, link copy s:<mime> s: MIME f:<mime> f: MIME 171
Drag & Drop API Drag & Drop 172
Drag & Drop API : card_dnd.html 173
Drag & Drop API [ HTML ] <section id="dropbox"> <canvas id="canvas" width="500" height="540"></canvas> </section> <section id="databox"> <img id="image1" width="100" height="80" src="g1.jpg"> <img id="image2" width="100" height="80" src="g2.jpg"> <img id="image3" width="100" height="80" src="g3.jpg"> <img id="image4" width="100" height="80" src="g4.jpg"> <img id="image5" width="100" height="80" src="g5.jpg"> <img id="image6" width="100" height="80" src="g6.jpg"> </section> [ JavaScript ] var canvas, drop; function initiate(){ var images=document.queryselectorall('#databox > img'); for(var i=0; i<images.length; i++){ images[i].addeventlistener('dragstart', dragged, false); drop=document.getelementbyid('canvas'); canvas=drop.getcontext('2d'); drop.addeventlistener('dragover', function(e){ e.preventdefault();, false); drop.addeventlistener('drop', dropped, false); 174
Drag & Drop API function dragged(e){ elem=e.target; e.datatransfer.setdata('text', elem.getattribute('id')); e.datatransfer.setdragimage(e.target, 0, 0); function dropped(e){ e.preventdefault(); var id=e.datatransfer.getdata('text'); var elem=document.getelementbyid(id); var posx=e.pagex-drop.offsetleft; var posy=e.pagey-drop.offsettop; canvas.drawimage(elem,posx,posy, 200, 200); window.addeventlistener('load', initiate, false); 175
Drag & Drop API : dnd_fileread.html 176
Drag & Drop API [ HTML ] <style type="text/css">.hover { border: 10px solid #000; background-color: #bbb; </style> <section id="content"> <h1>drag & Drop File I/O </h1> <p>.</p> <article> <input id="file" type="file"> <select id="encoding"> <option>euc-kr</option> <option>utf-8</option> </select> <button id="read"> </button><br /> <div> <span id="filename">file Name</span> <span id="filesize">file Size</span> </div> <textarea id="droparea" class="droparea" readonly style="width:600px; height:400px;"></textarea> </article> </section> 177
Drag & Drop API [ JavaScript ] window.onload = function() { var readbutton = document.getelementbyid("read"); readbutton.onclick = function(event) { readfile(document.getelementbyid("file").files[0]); var target = document.getelementbyid("droparea"); target.ondragover = function(event) { if(event.preventdefault) event.preventdefault(); target.ondragenter = function(event){ target.classlist.add('hover'); target.ondragleave = function(event){ target.classlist.remove('hover'); target.ondrop = function(event){ if(event.preventdefault) event.preventdefault(); target.classlist.remove('hover'); var filedata = event.datatransfer.files[0]; readfile(filedata); function readfile(file) { document.getelementbyid("filename").textcontent = file.name; document.getelementbyid("filesize").textcontent = "(" + file.size + "byte)"; var reader = new FileReader(); 178
Drag & Drop API ; reader.onload = function() { var display = document.getelementbyid("droparea"); display.textcontent = reader.result; ; reader.onerror = function(evt) { alert(evt.target.error.code); ; var encodinglist = document.getelementbyid("encoding"); var encoding = encodinglist.options[encodinglist.selectedindex].value; reader.readastext(file, encoding); 179
Multimedia API <video> <audio> API controls, autoplay, loop boolean. currenttime. duration. ended/paused. canplaytype(type). play(). pause(). 180
Multimedia API : video_play.html 181
Multimedia API [ HTML ] <video id="media" width="720" height="400"> <source src="trailer.mp4"> <source src="trailer.ogg"> </video> <nav> <div id="buttons"> <button type="button" id="play"> </button> </div> <div id="bar"> <div id="progress"></div> </div> <div style="clear: both"></div> </nav> [ JavaScript ] function initiate() { maxim=600; mmedia=document.getelementbyid('media'); play=document.getelementbyid('play'); bar=document.getelementbyid('bar'); progress=document.getelementbyid('progress'); play.addeventlistener('click', push, false); bar.addeventlistener('click', move, false); 182
Multimedia API function push(){ if(!mmedia.paused &&!mmedia.ended) { mmedia.pause(); play.innerhtml=' '; window.clearinterval(loop); else{ mmedia.play(); play.innerhtml=' '; loop=setinterval(status, 1000); function move(e){ if(!mmedia.paused &&!mmedia.ended){ var mousex=e.pagex-bar.offsetleft; var newtime=mousex*mmedia.duration/maxim; mmedia.currenttime=newtime; progress.style.width=mousex+'px'; function status(){ if(!mmedia.ended){ var size=parseint(mmedia.currenttime*maxim/mmedia.duration); progress.style.width=size+'px'; else{ progress.style.width='0px'; play.innerhtml='play'; window.clearinterval(loop); window.addeventlistener('load', initiate, false); 183
File API File, name : type : MIME Type ( null) size : lastmodifieddate : slice(start, length) : (start) length FileReader readasbinarystring(fileblob) readastext(fileblob, encoding) ( UTF-8) readasdataurl(file) dataurl result : error : 184
File API onload onerror Error NOT_FOUND_ERR(1) File SECURITY_ERR(2) Web Application Access File File File NOT_READABLE_ERR(4) File ENCODING_ERR(5) DataURL File Blob DataURL URL 185
File API : imgfile_read.html 186
File API [ HTML ] <section id="formbox"> <form name="form"> <p> :<br><input type="file" name="myfile" id="myfile"></p> </form> </section> <section id="databox">. </section> [ JavaScript ] function initiate(){ databox=document.getelementbyid('databox'); var myfiles=document.getelementbyid('myfile'); myfiles.addeventlistener('change', process, false); function show(e){ var result=e.target.result; databox.innerhtml+='<img src="'+result+'" width=300>'; 187
File API function process(e){ var files=e.target.files; databox.innerhtml=''; var file=files[0]; if(!file.type.match(/image.*/i)){ alert('.'); else{ databox.innerhtml+='name: '+file.name+'<br>'; databox.innerhtml+='size: '+file.size+' bytes<br>'; var reader=new FileReader(); reader.addeventlistener('load', show, false); //reader.onload=show reader.readasdataurl(file); 188
Web Storage API. 4KB. ((transaction).. / ( ), ( ),,.. 189
Web Storage API (Session) ( ). : sessionstorage.setitem(key, value); : sessionstorage.getitem(key) : sessionstorage.removeitem(key) : sessionstorage.clear(); (Local).,, storagearea :.( ) key : oldvalue : newvalue : url : URL 190
Web Storage API (Local),, localstorage.mykey = "myvalue"; localstorage["mykey"] = "myvalue"; localstorage.setitem("mykey", "myvalue"); var mykey = localstorage.mykey; var mykey = localstorage["mykey"]; var mykey = localstorage.getitem["mykey"]; delete localstorage.mykey; delete localstorage["mykey"]; localstorage.removeitem("mykey"); 191
Web Storage API (Session),, sessionstorage.mykey = "myvalue"; sessionstorage["mykey"] = "myvalue"; sessionstorage.setitem("mykey", "myvalue"); var mykey = sessionstorage.mykey; var mykey = sessionstorage["mykey"]; var mykey = sessionstorage.getitem["mykey"]; delete sessionstorage.mykey; delete sessionstorage["mykey"]; sessionstorage.removeitem("mykey"); 192
Web Storage API : memo_storage.html 193
Web Storage API [ HTML ] <h2> </h2> <textarea id="txtbox" onkeydown="savetext();" onkeyup="savetext();" cols="100" rows="10"> </textarea> <br> <input type="button" value=" " onclick="clr();" onkeyup="clr();"> <p id="info" style="display: none;">.</p> [ JavaScript ] function savetext() { info = document.getelementbyid("info"); info.style.display = "block"; localstorage.setitem("memo", msg.value); ; function pageload() { msg = document.getelementbyid("txtbox"); msg.value = localstorage.getitem("memo"); ; function clr() { msg.value = ""; localstorage.removeitem("memo"); info.style.display = "none"; ; 194
Indexed DB API IndexedDB key, value. JavaScript. key. IndexedDB CRUD. IndexedDB API SQL.. Same Origin Policy. 195
Indexed DB API 1. DataBase 2. DataBase ( ) ObjectStore 3. ObjectStore Index 4. CRUD 196
Indexed DB API DataBase IDBFactory window.indexeddb. open(string name) : IDBOpenDBRequest open(string name, long version) : IDBOpenDBRequest deletedatabase(string name) : IDBOpenDBRequest open() API, success. deletedatabase(). blocked.(idbdatabase.close()) IDBOpenDBRequest. success error. var db; var request = indexeddb.open("mytestdatabase"); request.onerror = function(event) { alert("why didn't you allow my web app to use IndexedDB?!"); ; request.onsuccess = function(event) { db = request.result; ; 197