Top Banner
GROW YOUR TALENT WITH US! Iasi, martie 2014 Speakers: Alexandra Constandache [email protected] Alexandru Pradais [email protected]
63

Fii Practic Frontend - BeeNear - laborator 4

May 11, 2015

Download

Education

BeeNear
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Fii Practic Frontend - BeeNear - laborator 4

GROW YOUR TALENT WITH US!

Iasi, martie 2014

Speakers: Alexandra Constandache [email protected]

Alexandru Pradais [email protected]

Page 2: Fii Practic Frontend - BeeNear - laborator 4

GROW YOUR TALENT WITH US!

Iasi, martie 2014

FRONTEND DEVELOPMENT – LABORATOR 4

Page 3: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Glitz

3

Page 4: Fii Practic Frontend - BeeNear - laborator 4

4

Page 5: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Audio & Video

5

The main idea is:

• Make noise / watch cats playing piano without the need of a plugin

» No more Flash

• A lot of video/audio formats supported

• It is as easy as adding an image with the <img> tag – Audio in fact uses the <audio> tag

– Video in fact uses the <video> tag

Page 6: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Audio

Audio <p>

Hear us rock out with our new song,

<i>Sesame Street Rubber Duckies</i>:

</p>

<audio src="rubberduckie.mp3" controls></audio>

SRC = file name to be played

CONTROLS = tell the browser to include a basic set of playback controls (with the style specific to each browser as shown below (picture from HTML5: The missing manual)

6

!Note: The <audio> and <video> elements must have both a start and an end tag. You can’t use empty element syntax, like <audio />.

Page 7: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Audio

In order to create your own controls we can use the following API methods: • play() — plays the audio

• pause() — pauses the audio

• canPlayType() — interrogates the browser to establish whether the given mime type can be played

• buffered() — attribute that specifies the start and end time of the buffered part of the file

• And the following properties • currentTime = playhead position (seconds)

• duration = media duration (seconds) – read only

• muted = is volume muted? (boolean)

• paused = is media paused? (boolean)

• volume = volume level (double)

7

Page 8: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Audio

Other <audio> attributes:

• preload – with the following possible values • auto – let the browser decide what to do

• metadata – the browser is told to download a small chunk of information (“metadata”) before playing – like the total length of the audio

• none – the browser is told to hold the download

• When the value of the preload attribute is in {metadata, none} the media is downloaded once it is started to play

• autoplay - start playback as soon as it can

• loop – specify whether the file should be played repeatedly

8

Page 9: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Audio

Have you met the codecs ? • In software, an audio codec is a computer program implementing

an algorithm that compresses and decompresses digital audio data according to a given audio file format or streaming media audio format.

• Famous HTML5 audio codecs: Ogg Vorbis, MP3, WAV • How do we know what works where?

– Using the source tag and type attribute:

<audio>

<source src="elvis.mp3" type='audio/mpeg; codecs="mp3"'>

<source src="elvis.oga" type='audio/ogg; codecs="vorbis"'>

<!-- add your fallback solution here -->

</audio>

– Use the canPlayType method which can return: Probably, maybe or an empty string.

» (why? Because the browser can only guess)

» audio.canPlayType('audio/ogg');

» audio.canPlayType('audio/ogg; codecs="vorbis"');

9

Page 10: Fii Practic Frontend - BeeNear - laborator 4

HTML5test.com says…

10

Page 11: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Video

Video • <video width="640" height="360“

src="http://www.youtube.com/demo/google_main.mp4"

controls autobuffer poster="whale.png" >

<p> Or you can

<a href="http://www.youtube.com/demo/google_main.mp4">

download the video </a> instead.

</p>

</video>

Attributes are similar to the audio tag with few exceptions:

• autobuffer – similar to the audio preload attribute

• poster – useful to display a frame of the video (as a .jpg, .png ….and so on) in case the video doesn’t load the video.

11

Page 12: Fii Practic Frontend - BeeNear - laborator 4

12

Page 13: Fii Practic Frontend - BeeNear - laborator 4

Audio – Video examples

• Check this online music player: • http://antimatter15.github.com/player/player.html

13

Page 14: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas

14

More cool stuff at http://www.html5canvastutorials.com/

Page 15: Fii Practic Frontend - BeeNear - laborator 4

HTML5 canvas

Getting started: • <canvas id="drawingCanvas" width="500" height="300"></canvas>

• Initialized as a blank borderless rectangle

• A little css never hurt nobody canvas {

border: 1px dashed black;

}

• To start working with the canvas, we need the reference to the canvas: var canvas = document.getElementById("drawingCanvas");

• Second, we need to setup the 2D context (well there is no 3D context yet) var b_context = b_canvas.getContext("2d")

function draw()

{

var canvas = document.getElementById("drawingCanvas");

var context = canvas.getContext("2d");//future 3D

}

15

Page 16: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas

Drawing in Canvas Context:

The esential functions are: beginPath()

closePath()

stroke()

fill()

Properties: fillStyle = (CSS color,pattern,gradient)

strokeStyle= (CSS color,pattern,gradient)

o Drawing lines o moveTo(x, y)

o lineTo(x, y)

16

context.moveTo(10,10); context.lineTo(400,40); context.stroke(); //draws a line from 10-10 to 400-400

Page 17: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas

Modifying lines (must be set before stroke)

• Linewidth = width of the line in pixels • context.lineWidth = 10;

• Strokestyle = color of the line in HTML color name and color code • // Set the color (brick red) using an HTML color code:

context.strokeStyle = "#cd2828";

• // Set the color (brick red) using the rgb() function:

context.strokeStyle = "rgb(205,40,40)";

• linecap = decide the cap of the line • butt – squared-off edge

• round

• square - (which looks the same as butt, but extends the line

an amount equal to half its thickness on each end).

17

Page 18: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas Drawing lines

// Set the line width and color (for all the lines).

context.lineWidth = 20; context.strokeStyle = "rgb(205,40,40)"; // Draw the first line, with the standard butt

ending. context.moveTo(10, 50); context.lineTo(400, 50); context.lineCap = "butt"; context.stroke(); // Draw the second line, with a round cap. context.beginPath(); context.moveTo(10, 120); context.lineTo(400, 120); context.lineCap = "round"; context.stroke(); // Draw the third line, with a square cap. context.beginPath(); context.moveTo(10, 190); context.lineTo(400, 190); context.lineCap = "square"; context.stroke();

18

Page 19: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas

Drawing and filling triangles or any other polygons context.moveTo(250,50);

context.lineTo(50,250);

context.lineTo(450,250);

context.lineTo(250,50);

context.lineWidth = 10;

context.strokeStyle = "red";

context.stroke();

• Filling the triangle means that we need to close the line path with closePath(), pick a color using fillStyle and call fill()

context.closePath();

context.fillStyle = "blue";

context.fill();

closePath also connects the begin point with the last drawn point

Calling fill after stroke means that the stroke will be overlapped with the fill color, if we do not want that, this means stroke must be called after fill

o Drawing rectangles • fillRect(x, y, width, height)

• strokeRect(x, y, width, height)

• clearRect(x, y, width, height)

19

Page 20: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas

Drawing text

Context: Context.font= {font}

Context.textAlign={start,end,left,right,center};

Context.textBaseline=

{top,hanging,middle,alphabetic,ideographic,bottom};

o Drawing o Context.fillText(text,x,y);

20

Page 21: Fii Practic Frontend - BeeNear - laborator 4

HTML5 Canvas

This is just a taste of it…. Canvas can do a lot of things: • Draw different arcs

• Draw with gradients

• Draw with transparency

• Draw full images

• Transform the context

• Make composite operations by indicating how overlapping figures must look

• Interact with the user

You can read more about them on: • http://www.html5canvastutorials.com/

• https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial

21

Page 22: Fii Practic Frontend - BeeNear - laborator 4

Canvas demos

• http://htmlfive.appspot.com/static/gifter.html

• http://html5demos.com/canvas-grad

22

Page 23: Fii Practic Frontend - BeeNear - laborator 4

23

Page 24: Fii Practic Frontend - BeeNear - laborator 4

Geolocation

24

Who?

• Well, you...that's who...

What?

• Browsing...that's what!

Where?

• Well, now we're getting someWHERE(?)

Page 25: Fii Practic Frontend - BeeNear - laborator 4

Geolocation

25

So, what is Geolocation ?

• Geolocation is a feature that lets you find out where in the world your visitors are.

Scary part

• Pretty precise

• can get your geographical coordinates down to a couple of hundred m

Good part

• It's polite about it

• Always asks for permission

Page 26: Fii Practic Frontend - BeeNear - laborator 4

Geolocation

26

How does it do it?

• Location provider service. Ex. Google Location Services

Location provider service determines location depending on connection

• Fixed connection to internet

• public IP address of the machine used for acces to the web

• Wireless connection • WAPs - wireless access points

– the ones closest are retrieved from a database

– position is triangulated based on them

• Mobile connection

• Cellphone towers - position is triangulated based on these

• Bonus - GPS equipped devices.

Page 27: Fii Practic Frontend - BeeNear - laborator 4

Geolocation

27

How to use geolocation in a page/app?

One object - 3 methods

• Geolocation "provider"

• navigator.geolocation browser object

• "Provider" methods

• getCurrentPosition()

– get's the position at a certain moment

• watchPosition()

– monitors changes in the position of the client

• clearWatch()

– stops monitoring position

Page 28: Fii Practic Frontend - BeeNear - laborator 4

Geolocation - getCurrentPosition

28

Page 29: Fii Practic Frontend - BeeNear - laborator 4

Geolocation - watchPosition

29

Page 30: Fii Practic Frontend - BeeNear - laborator 4

Geolocation - position data

30

Page 31: Fii Practic Frontend - BeeNear - laborator 4

Web Workers

31

What's one thing that internet users all over fear and hate?

• An unresponsive web page.

Cause?

• Page contained maybe some code or loading procedure that takes too tooooooooooooooooooooooooooooooooooooooo long to finish executing.

Page 32: Fii Practic Frontend - BeeNear - laborator 4

Web Workers

32

Who and what can save us?

• Web Workers

Page 33: Fii Practic Frontend - BeeNear - laborator 4

Web Workers

33

What is a web worker?

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.

What is does is

• take care of time consuming tasks in the background

• so that

• the page remains active for the user to click through it

Page 34: Fii Practic Frontend - BeeNear - laborator 4

Web Workers

34

How does the page talk to the worker?

• workerobject.postMessage(messageObject)

• method used to send messages

–from worker to page

– from page to worker

• workerobject.onmessage = function dosomething with response

• event used to listen to messages sent between page and worker

Page 35: Fii Practic Frontend - BeeNear - laborator 4

Web Workers - Communication model

35

Page 36: Fii Practic Frontend - BeeNear - laborator 4

Web Workers - how to

36

How to call on the help of a web worker for long running tasks.

• Put the code for the task in a separate .JS file (example.js)

• Inside the code create a new worker object

• var worker

• Assign the task to the worker

• worker = new Worker('example.js')

• Tell the worker to start work

• worker.postMessage('some message').

• Listen for signs that the worker has finished the task

• worker.onMessage = function dosomethingwithresult() {...}

Page 37: Fii Practic Frontend - BeeNear - laborator 4

Web Workers

37

Limitations of the web worker

• cannot access any information on the parent web page

• cannot access the DOM

• cannot update elements of the page

• cannot update global variables

• all data needs to be passed with the postMessage method

Page 38: Fii Practic Frontend - BeeNear - laborator 4

HTML5 - WEB FORMS

38

HTML forms are simple HTML controls you use to collect information from website visitors

Page 39: Fii Practic Frontend - BeeNear - laborator 4

HTML FORMS – the basics

Form fields are objects that allow the visitor to enter information - for example text boxes, drop-down menus or radio buttons.

When the visitor clicks a submit button, the content of the form is usually sent to a program that runs on the server. However, there are exceptions…

is sometimes used to create magic with form fields. An example could be when turning options in a drop-down menu into normal links.

! Note: Unlike a table, forms are not visible on the page.

39

Page 40: Fii Practic Frontend - BeeNear - laborator 4

The simplest possible form is the single text box that adorns search engines like Google

40

Page 41: Fii Practic Frontend - BeeNear - laborator 4

HTML Forms – the basics

With the <form> tag you can add to your web pages a guestbook, order forms, surveys, get feedback or whatever. <form><!--FORM ELEMENTS ENCLOSED BETWEEN FORM START AND FORM END

TAGS--></form>

To let the browser know where to send the content we add these properties to the <form> tag:

• action = “address” • Tells the form where its contents will be sent to.

– cgi program e.g. action="http://www.web-wise-wizard.com/cgi-bin/orders.cgi"

– mailto: e.g. action="mailto:[email protected]" (Netscape browsers only)

• method=post or get • How the data is going to be sent. It can have the value get, which is default,

and latches the form information onto a web address, or post, which (essentially) invisibly sends the form’s information.

41

Page 42: Fii Practic Frontend - BeeNear - laborator 4

A well-designed form, divides itself into logical chunks using the <fieldset> element. Each chunk gets a title, courtesy of the <legend> element.

<label> element is used to label the input. <fieldset>

<legend>Contact Details</legend>

<label for="name">Name <em>*</em></label>

<input id="name"><br>

<label for="telephone">Telephone</label>

<input id="telephone"><br>

<label for="email">Email <em>*</em></label>

<input id="email"><br>

</fieldset>

42

Page 43: Fii Practic Frontend - BeeNear - laborator 4

HTML Forms – the input

<input>

• ask for information in one of several different way (there can be as many input areas as you wish)

• is the daddy of the form world • More information: http://www.htmldog.com/reference/htmltags/input/

<input type=“text”> or simply <input> a standard textbox.

<input type=“password”> similar to the textbox, but the characters typed will be hidden.

<input type=“checkbox”> is a checkbox, which can be toggled on and off by the user.

<input type=“radio”> similar to a checkbox, the user can only select one radio button in a group.

<input type=“submit”> is a button that when selected will submit the form.

<input type=“image”> similar to submit input but it can display an image

<input type=“reset”> clears the visitor’s selections and text from all the input controls.

<input type=“button”> displays a basic button

43

!Note: it is useful to have an id for each input type.

Page 44: Fii Practic Frontend - BeeNear - laborator 4

HTML Forms – the Text Area

<textarea>

• Shows a large text box that can fit multiple lines of text.

• The anticipated number of rows and columns can be defined with rows and cols attributes, although you can manipulate the size to your heart’s content using CSS.

44

<textarea rows="5" cols="20"> A big load of text </textarea>

Page 45: Fii Practic Frontend - BeeNear - laborator 4

<select>

• Shows a list where your visitor can select one or more items. You add an <option> element for each item in the list.

45

<select> <option>Option 1</option> <option>Option 2</option> <option value="thirdOption"> Option 3 </option> </select>

When the form is submitted, the value of the selected option will be sent. This value will be the text between the selected opening and closing option tag unless an explicit value is specified with the value attribute, in which case this will be sent instead.

If the multiple property is present <select multiple>..</select> then we are dealing with a multiple selection list

Page 46: Fii Practic Frontend - BeeNear - laborator 4

HTML Forms – the input

<input> • HTML5 introduces a number of new input types.

• give hints to the browser about what type of keyboard layout to display for on-screen keyboards.

46

Page 47: Fii Practic Frontend - BeeNear - laborator 4

Input Type Description

url For entering a URL. It must start with a valid URI scheme, (for example http://, ftp:// or mailto:).

tel For entering phone numbers. It does not enforce a particular syntax for validation, so if you want to ensure a particular format, you can use pattern.

email For entering email addresses. By default it will only take one, but if the multiple attribute is provided, a comma separated list of email addresses is valid.

search A text input field styled in a way that is consistent with the platform's search field.

number For numeric input, can be any rational integer or float value.

47

http://www.html5rocks.com/

Page 48: Fii Practic Frontend - BeeNear - laborator 4

Input Type Description

color For choosing colors.

range For number input, but unlike the number input type, the value is less important. It is displayed to the user as a slider control.

datetime For entering a date and time value where the time zone is provided as GMT.

datetime-local For entering a date and time value where the time zone provided is the local time zone.

48

http://www.html5rocks.com/

Page 49: Fii Practic Frontend - BeeNear - laborator 4

HTML5 – placeholder

The placeholder attribute

• Provides a hint to the user about what is expected to be in the input by displaying its value as light text until the element gets focus.

49

Page 50: Fii Practic Frontend - BeeNear - laborator 4

The datalist element • Provides a suggested input values to associate with a form field

<input type="text" id="inpChocType" list="chocType">

<datalist id="chocType">

<option value="white" />

<option value="milk" />

<option value="dark" />

</datalist>

The autocomplete attribute • You don’t want the browser to automatically fill in data based on

users past entries -> autocomplete = “off”

The autofocus attribute • Specify that the element is the primary form element and it is

automatically focused

50

Page 51: Fii Practic Frontend - BeeNear - laborator 4

HTML – form events

onClick function testSelect(form) { alert (form.list.selectedIndex); }

<FORM NAME="myform" ACTION="" METHOD="GET">

<INPUT TYPE="button" NAME="button" Value="Test" onClick="testSelect(this.form)">

<SELECT NAME="list" SIZE="3">

<OPTION>This is item 1

<OPTION>This is item 2

<OPTION>This is item 3

</SELECT>

51

Page 52: Fii Practic Frontend - BeeNear - laborator 4

HTML – form events

onFocus -- an event is triggered with a form object gets input focus (the insertion point is clicked there).

onBlur -- an event is triggered with a form object loses input focus (the insertion point is clicked out of there).

onChange -- an event is triggered when a new item is selected in a list box. This event is also trigged with a text or text area box loses focus and the contents of the box has changed.

onSelect -- an event is triggered when text in a text or text area box is selected.

onSubmit -- an event is triggered when the form is submitted to the server (more about this important hander later in the column).

52

Page 53: Fii Practic Frontend - BeeNear - laborator 4

HTML Forms – the input

<input> • built-in validation for some input types like email and url. On

other elements, you can indicate a valid input format by providing a regular expression in the the pattern attribute.

53

Why do we need validation? 1. Keep the data clean 2. Improve the user

experience

Page 54: Fii Practic Frontend - BeeNear - laborator 4

HTML5 – input validation

Validation constraint attributes: pattern

• specifies a regular expression* used to validate an input field • <input type="text" id="partNumber" pattern="[A-Z]{3}[0-9]{4}"/>

• Allowed: 3 uppercase letter & 4 digit

required

• If it is present -> the field must not be empty before the form will be submitted

• <input type="text" required id="partNumber" pattern="[A-Z]{3}[0-9]{4}"/>

min , max & step • for numeric input types like number or range

• the min and max attributes are also used on any of the date type inputs.

54 * http://www.marksanborn.net/howto/learning-regular-expressions-for-beginners-the-basics/

Page 55: Fii Practic Frontend - BeeNear - laborator 4

maxlength

• maximum length of an input or textbox • <input type="text" id="83filename" maxlength="12"/>

nonvalidate

• Allow the user to submit non-valid data <form role="form" novalidate>

<label for="inpEmail">Email address</label>

<input type="email" id="inpEmail">

</form>

55

Page 56: Fii Practic Frontend - BeeNear - laborator 4

Validation constraint APIs* for handling custom validation

• Custom error • Check if an element is valid or why it is invalid New JavaScript APIs and properties that are available on input elements

56 * http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/

API Use

willValidate Property that returns true or false if the element is a candidate for validation.

validity Property that returns a ValidityState object representing the validity states of the element.

validationMessage Property that returns a string with the reason the object failed the validation test.

checkValidity() Returns true if the element satisfies all of it’s constraints, and false otherwise.

setCustomValidity() Sets a custom validation message and the customErrorproperty of the ValidityState object to true.

The invalid event • Triggered if the checkValidity() returns false

Page 57: Fii Practic Frontend - BeeNear - laborator 4

var elem = document.getElementById("email_addr_confirm");

elem.addEventListener("blur", verifyEmail);

function verifyEmail(input) {

input = input.srcElement;

if (input.value != document.getElementById('email_addr').value) {

// the provided value doesn’t match the primary email address

input.setCustomValidity('The two email addresses must match.');

} else {

// input is valid -- reset the error message

input.setCustomValidity('');

}

}

57

Verify that the user has provided the correct email address on a sign up form where they’re asked to enter it twice.

Page 58: Fii Practic Frontend - BeeNear - laborator 4

HTML – forms styling

With the support of CSS3 • HTML5 also introduces a number of new pseudo-classes that can be used to

style inputs based on their value or attributes, making it easier for users to understand if they’ve filled the form out properly before trying to submit it.

• :valid and :invalid - explicitly sets the style for an element when the input is valid/invalid.

• :required and :optional - sets the style for elements that are required or optional.

• :in-range and :out-of-range - styling for elements that support the min and max attribute

58

Page 59: Fii Practic Frontend - BeeNear - laborator 4

JavaScript & Getting Data From Forms

The input can be retrieved with the good old document.getElementById

For text input types, the value is in the “value” property.

• Example: Type something: <input type="text" id="user_text">

var popup_message = "You typed: " + document.getElementById("user_text").value;

(text, numeric, textarea…)

59

Page 60: Fii Practic Frontend - BeeNear - laborator 4

For drop down lists we can use the following

• selectedIndex • oSelectOne = oForm.elements["select_one_element_name"];

• index = oSelectOne.selectedIndex;

• and according to this index we can get the value selected • var selected_option_value = oSelectOne.options[index].value;

• Or we can get the text shown • var selected_option_text = oSelectOne.options[index].text;

• Or we can iterate through the options and test the selected property (useful in the case of multiple selection list)

60

Page 61: Fii Practic Frontend - BeeNear - laborator 4

Checkboxes and radio value retrieval we can use the following properties:

• value (usually used to get the value of the selected one)

• checked (true/false)

61

Page 62: Fii Practic Frontend - BeeNear - laborator 4

Bibliography

HTML5: The Missing Manual by Matthew MacDonald

JavaScript by Mozilla Developer Network

• https://developer.mozilla.org/en-US/docs/Web/JavaScript

DIVE INTO HTML5 by Mark Pilgrim http://diveinto.html5doctor.com/

HTML5 Doctor: http://html5doctor.com/ Other HTML5 demos …well check this out: http://html5demos.com/

HTML Dog http://www.htmldog.com/

For beginners: • http://www.w3.org/community/webed/wiki/HTML/Training

• http://www.w3.org/community/webed/wiki/HTML/Elements

62

Page 63: Fii Practic Frontend - BeeNear - laborator 4

Thank you!

63