0
New JavaScript APIs                               in HTML5                              Canvas, SVG, WorkersDoncho MinkovT...
Table of Contents New JavaScript APIs New Selectors Canvas JavaScript API Web Workers Drag and Drop HTML5 Storage H...
New JavaScript APIsWhat a programmer must know?
New JavaScript APIs New selectors Threading (Web Workers) UI APIs   Canvas   Drag and Drop   Local and Session Stora...
New Selectors
New Selectors In HTML5 we can select elements by ClassName var elements = document.getElementsByClassName(entry); Moreov...
New Selectors (2) Selecting the first   div met var elements = document.querySelector("div"); Selecting the first   item...
CanvasJavaScript API  How to Manipulate Canvas Dynamically?
Canvas Canvas  Dynamic, Scriptable rendering of 2D images  Uses JavaScript to draw  Resolution-dependent bitmap  Can ...
Canvas Properties and                               Methods fillStyle  Sets the drawing color  Default fillStyle is sol...
Canvas Properties and                            Methods (2) strokeStyle  Sets the stroke color strokeRect(x, y, width,...
Canvas Paths What is a Path?   Something that is about to be drawn    It is not drawn yet  context.beginPath();  contex...
CanvasLive Demo
Web WorkersMultithreading in JavaScript
What are Web Workers? API for running scripts   in the background   Independently of any user interface scripts Workers...
What are Web Workers? (2) Workers are separate JavaScript     processes running in separate threads   Workers execute co...
What are Web Workers? (3) If we call function by                       setTimeout, the execution of script and UI are sus...
What are Web Workers? (4) Messages are send to all      threads in our application:                                      ...
Web Workers  Live Demo
Drag and Drop  Drag and Drop
Drag and Drop To make an element draggable  Give the element a draggable attribute  Set an event listener for    drags...
Draggable Example<h1>Some things to drag</h1>           Simple Drag and Drop.html  <ul ondragstart="dragStart(event)">    ...
Drop Event To accept a drop   The drop target has to listen to the ondrop    event Two more events should be hooked too...
Drag And Drop   Live Demo
HTML5 Storage  Local and Session
Local Storage Local Storage   Store data locally   Similar to cookies, but can store much larger    amount of data   S...
Local Storage Example Local Storagefunction saveState(text){  localStorage["text"] = text;}function restoreState(){  retu...
Session Storage Session Storage  Similar to Local Storage  Lasts as long as browser is open  Opening page in new windo...
Session Storage Example Session Storagefunction incrementLoads() {  if (!sessionStorage.loadCounter) {     sessionStorage...
HTML5 Storages    Live Demo
HTML DOM Extensions                      31
HTML DOM Extensions HTML DOM Extensions:  getElementsByClassName()  innerHTML  hasFocus  getSelection()              ...
HTML DOM Extensions       Live Demo
Event Listeners   How to Listen for Something to Happen?
Event Listeners Event Listener is an event that tracks for something to happen   i.e. a key to be pressed, a mouse click...
Registering Event Listener                                      Example   Adding a click event listener to a div element ...
Event Listeners    Live Demo
New JavaScript APIs in HTML5    курсове и уроци по програмиране, уеб дизайн – безплатно     BG Coder - онлайн състезателна...
Exercises1.    Write wrapper function as follows:      $(ID) to return either a single element,       whose ID is the one...
Exercises (2)2.    Write an event delegate function member of      the Event global object e.g.      Event.delegate("selec...
Exercises (3)3.    Write a client-side based web application      that consists of a trash bucket and lots of      trash i...
With Drag   Exercises (4) Clean the Trash   example                                                 42
Free Trainings @ Telerik Academy "Web Design with HTML 5, CSS      3 and    JavaScript" course @ Telerik Academy       h...
Upcoming SlideShare
Loading in...5
×

19. New JavaScript Apis in HTML5 - Web Front-End

3,094

Published on

What a programmer must know about the new JavaScript APIs in HTML5?
Telerik Software Academy: http://html5course.telerik.com
The website and all video materials are in Bulgarian

Table of contents:
New JavaScript APIs
New Selectors
Canvas JavaScript API
Web Workers
Drag and Drop
HTML5 Storage
HTML DOM Extensions
Event Listeners

Published in: Technology, Design
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,094
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
84
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "19. New JavaScript Apis in HTML5 - Web Front-End"

  1. 1. New JavaScript APIs in HTML5 Canvas, SVG, WorkersDoncho MinkovTechnical Trainerhttp://www.minkov.itTelerik Software Academyacademy.telerik.com
  2. 2. Table of Contents New JavaScript APIs New Selectors Canvas JavaScript API Web Workers Drag and Drop HTML5 Storage HTML DOM Extensions Event Listeners 2
  3. 3. New JavaScript APIsWhat a programmer must know?
  4. 4. New JavaScript APIs New selectors Threading (Web Workers) UI APIs  Canvas  Drag and Drop  Local and Session Storage Extension to HTML Document 4
  5. 5. New Selectors
  6. 6. New Selectors In HTML5 we can select elements by ClassName var elements = document.getElementsByClassName(entry); Moreover there’s now possibility to fetch elements that match provided CSS syntax var elements = document.querySelectorAll("ul li:nth-child(odd)"); var first_td = document.querySelector("table.test > tr > td"); 6
  7. 7. New Selectors (2) Selecting the first div met var elements = document.querySelector("div"); Selecting the first item with class SomeClass var elements = document.querySelector(".SomeClass"); Selecting the first item with id someID var elements = document.querySelector("#someID"); Selecting all the divs in the current containervar elements = document.querySelectorAll("div"); 7
  8. 8. CanvasJavaScript API How to Manipulate Canvas Dynamically?
  9. 9. Canvas Canvas  Dynamic, Scriptable rendering of 2D images  Uses JavaScript to draw  Resolution-dependent bitmap  Can draw text as well <canvas id="ExampleCanvas" width="200" height="200"> This text is displayed if your browser does not support HTML5 Canvas. </canvas> var example = document.getElementById(ExampleCanvas); var context = example.getContext(2d); context.fillStyle = "rgb(255,0,0)"; context.fillRect(30, 30, 50, 50); 9
  10. 10. Canvas Properties and Methods fillStyle  Sets the drawing color  Default fillStyle is solid black  But you can set it to whatever you like fillRect(x, y, width, height)  Draws a rectangle  Filled with the current fillStyle 10
  11. 11. Canvas Properties and Methods (2) strokeStyle  Sets the stroke color strokeRect(x, y, width, height)  Draws an rectangle with the current strokeStyle  strokeRect doesn’t fill in the middle  It just draws the edges clearRect(x, y, width, height) clears the pixels in the specified rectangle 11
  12. 12. Canvas Paths What is a Path?  Something that is about to be drawn  It is not drawn yet context.beginPath(); context.moveTo(0, 40); context.lineTo(240, 40); context.moveTo(260, 40); context.lineTo(500, 40); context.moveTo(495, 35); context.lineTo(500, 40); context.lineTo(495, 45); 12
  13. 13. CanvasLive Demo
  14. 14. Web WorkersMultithreading in JavaScript
  15. 15. What are Web Workers? API for running scripts in the background  Independently of any user interface scripts Workers are expected to be long-lived  Have a high start-up performance cost and a high per-instance memory cost Might be partially replaced by Window.setTimeout() function 15
  16. 16. What are Web Workers? (2) Workers are separate JavaScript processes running in separate threads  Workers execute concurrently  Workers don’t block the UI  Workers allow you to extract up to the last drop of juice from a multicore CPU  Workers can be dedicated (single tab) or shared among tabs/windows  Workers will be persistent too (coming soon)  They’ll keep running after the browser has quit 16
  17. 17. What are Web Workers? (3) If we call function by setTimeout, the execution of script and UI are suspended  When we call function in worker, it doesn’t affect UI and execution flow in any way To create Worker, we put JavaScriptin separate file and create new Worker instance: var worker = new Worker(‘extra_work.js); We can communicate with worker using postMessage function and onmessage listener 17
  18. 18. What are Web Workers? (4) Messages are send to all threads in our application: main.js:var worker = new Worker(‘extra_work.js);worker.onmessage = function (event) { alert(event.data); }; extra_work.js://do some work; when done post message.// some_data could be string, array, object etc.postMessage(some_data); 18
  19. 19. Web Workers Live Demo
  20. 20. Drag and Drop Drag and Drop
  21. 21. Drag and Drop To make an element draggable  Give the element a draggable attribute  Set an event listener for  dragstart that stores the data being dragged  The event handler typically needs to check that the selection being dragged is not a text  Store data into the DataTransfer object  Set the allowed effects  Copy, move, link, or some combination 21
  22. 22. Draggable Example<h1>Some things to drag</h1> Simple Drag and Drop.html <ul ondragstart="dragStart(event)"> <li draggable="true">Pesho</li> <li draggable="true">Gosho</li> <li draggable="true">Penka</li> <li draggable="true">Mariika</li> </ul><script> var safePlace = text/safaPlace; function dragStart(event) { event.dataTransfer.setData(safePlace, event.target.dataset.value); event.dataTransfer.effectAllowed = move; }</script> 22
  23. 23. Drop Event To accept a drop  The drop target has to listen to the ondrop event Two more events should be hooked too  The dragenter event  To report whether the drop target is to accept  The dragover event  To specify what is to be shown to the user 23
  24. 24. Drag And Drop Live Demo
  25. 25. HTML5 Storage Local and Session
  26. 26. Local Storage Local Storage  Store data locally  Similar to cookies, but can store much larger amount of data  Same Origin Restrictions  localStorage.setItem(key, value)  localStorage.getItem(key) Local and Session Storages can only store strings! 26
  27. 27. Local Storage Example Local Storagefunction saveState(text){ localStorage["text"] = text;}function restoreState(){ return localStorage["text"];} Same asfunction saveState(text){ localStorage.setValue("text", text);}function restoreState(){ return localStorage.getValue("text");} 27
  28. 28. Session Storage Session Storage  Similar to Local Storage  Lasts as long as browser is open  Opening page in new window or tab starts new sessions  Great for sensitive data (e.g. banking sessions) 28
  29. 29. Session Storage Example Session Storagefunction incrementLoads() { if (!sessionStorage.loadCounter) { sessionStorage["loadCounter"] = 0; } var currentCount = parseInt(sessionStorage["loadCounter"]); currentCount++; sessionStorage["loadCounter"] = currentCount; document.getElementById("countDiv").innerHTML = currentCount;} 29
  30. 30. HTML5 Storages Live Demo
  31. 31. HTML DOM Extensions 31
  32. 32. HTML DOM Extensions HTML DOM Extensions:  getElementsByClassName()  innerHTML  hasFocus  getSelection() 32
  33. 33. HTML DOM Extensions Live Demo
  34. 34. Event Listeners How to Listen for Something to Happen?
  35. 35. Event Listeners Event Listener is an event that tracks for something to happen  i.e. a key to be pressed, a mouse click, etc. Available in JavaScript  addEventListener() registers a single event listener on a single target  The event target may be  A single node in a document  The document itself  A window 35
  36. 36. Registering Event Listener Example Adding a click event listener to a div element document.GetElementById("someElement"). addEventListener("click", function (e) { alert("element clicked"); }, false); 36
  37. 37. Event Listeners Live Demo
  38. 38. New JavaScript APIs in HTML5 курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  39. 39. Exercises1. Write wrapper function as follows:  $(ID) to return either a single element, whose ID is the one passed or null  $$(selector) to return an array of elements or empty array with results;  Use mapping to existing DOM methods  e.g. getElementByClassName, querySelectorAll 39
  40. 40. Exercises (2)2. Write an event delegate function member of the Event global object e.g. Event.delegate("selector", "eventName", handlerName) using the previously written functions to match selectors.  Map the global listeners to the document or body element;  Use w3c style events. $("#id").delegate(".clickable", "click", function(){ alert("Clicked!");}); 40
  41. 41. Exercises (3)3. Write a client-side based web application that consists of a trash bucket and lots of trash items in the browser window. Implement functionality:  To drag the trash items  To open the bucket when a trash item is being dragged over it and close it when there is no trash dragged  To put the trash item in the bucket, i.e. make it disappear from the browser window 41
  42. 42. With Drag Exercises (4) Clean the Trash example 42
  43. 43. Free Trainings @ Telerik Academy "Web Design with HTML 5, CSS 3 and JavaScript" course @ Telerik Academy  html5course.telerik.com Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×