30
© Liron Blecher JavaScript Liron Blecher

© Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

Embed Size (px)

Citation preview

Page 2: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

Age

nda

• JavaScript Language

• DOM

• Events

• Timers

• Debug

• Forms

• JavaScript and CSS

• AJAX

• jQuery JavaScript Library

Page 3: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - preface

Runs whenever it gets written• <script src=“script.js”></script>

• In Html5 there’s no need to add type=“text/javascript”

Case sensitive !!!

For optimal debugging install Firebug for Firefox or use the developer console in Chrome/IE using F12

• Enable to write to log

• console.log (“…”);

• also available are: debug, info, warn and error

3

Page 4: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - language

‘==‘ comparison• means to compare values even if types are different

• “5” == 5 will return true

• “” == 0 will also return true…

‘===‘ comparison• Strict compare of value and types

To declare a new variable• var x = 10;

Anything that is not defined can be accessed and its value will be undefined

4

Page 5: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - functions

Functions parameters• If you call a function with more parameters than declared, the

rest will be ignored

• If you call a function with less parameters than declared, the missing parameters will have an ‘undefined’ value

5

Page 6: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - arrays

Arrays are dynamic• var arr = [];

• var arr = [50, 60, “mouse”];

• var arr = new Array();

• arr[0] = 80;

• arr[100] = “dog”;

• arr.push(80); - will add 80 to the end of the array

• arr.length;

• arr.sort();

6

Page 7: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - numbers

All numbers are actually 64 bit floating point

5 + “5” will return “55”

5 * “b” will return NaN //Not a Number

var num = Number (“555”); //convert to a number

or: parseInt() / parseFloat()

if (isNan(num)) … //if num is not a number

Math.round (200.6);

Math.random();

7

Page 8: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - strings

Strings• str.length

• str.toUpperCase()

• str.slice (0,4)

• str.split (“;”)

Reference:• https://developer.mozilla.org/en/JavaScript/Reference

8

Page 9: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - dates

Dates• var d = new Date();

• var d = new Date(2000, 0, 12);

• Months: 0 – 11

• d.getFullYear() -> YYYY

• d.getDate() -> 1..31 (day of month)

• d.getDay() -> 0..6 (day of week)

• Use d.getTime() when comparing dates

9

Page 10: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - objects

Objects• var player = new Object();

• player.name = “john”;

• player.rank = 1;

• var player = {name: “john”, rank: 1};

• Get value• console.log (player.name);

• player.details = function () {//this.name ...

}

• player.details();

10

Page 11: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - DOM

JavaScript runs inside a web page

The way a webpage is represented in JS is called DOM (Document Object Model)

A DOM is a tree structure of the HTML page

Each object is called a Node (with different types); the three most common are:

• Element

• Attribute

• Text

11

Page 12: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - DOM

Element nodes don’t contain text – they have text elements as children)

To get element using an ID:• var head = document.getElementById (“header”);

To get element using tag name:• var links = document.getElementsByTagName (“a”);

• var cells = document.getElementsByClassName (“cell”);

Returned value(s) are references to DOM elements

12

Page 13: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - DOM

Might return empty arrays

Any change you make to a DOM element is immediately changed in the browser

Examples for methods and properties:• links[0].nodeType

• head.innerHTML

• links[0].childNodes

13

Page 14: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - DOM

To create a new DOM element:

1. Create a new detached element:document.createElement() or document.createTextNode(“…”)

2. Add it to another DOM element:header.appendChild(…) or header.insertBefore(…)

14

Page 15: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

DEMO

Browser console

15

Page 16: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - events

Events might be generated one time – window.onload or multiple times – onclick, onfocus (when a user enters a field), onblur (when a user leaves a field)

There are 3 ways to listen to events:

1. Write JS in the HTML

2. element.event = …example: myElement.onclick = function () {…};

3. document.addEventListener (‘click’, func);(in IE8: attachEvent(‘onclick’, func);

16

Page 17: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - events

If you want your code to run after the page has been loaded use:window.onload

• It will run once per page

window is the JS object representing the browser window

17

Page 18: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

DEMO

click

18

Page 19: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - timers

There are two ways to postpone code execution:

1. var tout = setTimeout (func, 1000) – will occur only once (aftet 1000 milliseconds)

2. var intr = setInterval (func, 2000) – will run every 2000 milliseconds

This methods returns an object that is used to stop the func by calling:

• clearTimeout(tout) or clearInterval(intr)…

19

Page 20: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - debug

In Firefox use Firebug

Remember: JS is case sensitive

In Firebug you can use right click -> inspect DOM tab

Add breakpoints

And more…

20

Page 21: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - forms

To access a form:• document.forms.formname

main form event: onsubmit = function(…)• return false to prevent the form from submitting

To hide an element (relevant anywhere):• document.getElementBy…().style.display = ‘none’

• To show: … style.display = ‘block’

21

Page 22: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

DEMO

examples.fileupload

22

Page 23: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript – JS and CSS

CSS values are named slightly different in JS• css: font-weight js: fontWeight

To set the class attribute:• myElement.classname = “…”

You might need to work with string methods in order to add/remove classes (instead of setting the entire attribute value)

• Example: document.getElementBy…().classname = “…”;

23

Page 24: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - AJAX

Create• IE: window.ActiveXObject (microsoft.XMLHTTP)

• Rest: new XMLHttpRequest()

• To check if XMLHttpRequest exists:• var myRequest;

• if (window.XMLHttpRequest) { myRequest = new XMLHttpRequest();

else {myRequest = window.ActiveXObject (microsoft.XMLHttpRequest);

24

Page 25: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - AJAX

Setup• myRequest.onreadystate = function {…}

• ‘onreadystate’ is called multiple times for each AJAX request.

• The important state is: • myRequest.readystate == 4

Use• myRequest.open (“GET”, “http://www...”, true);

• myRequest.send (…);

• myRequest.responseText is the returned value

25

Page 26: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - jQuery

External JS library that simplifies common tasks

Uses selectors (like CSS) to find DOM elements• jQuery (“#myDiv”).addClass (“…”) =

document.getElementById(“myDiv”)…

• jQuery (“.someClass”)…

• jQuery (“p”)…

Enable changes on sets of elements• Smart use of “this” inside a function

26

Page 27: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - jQuery

Conditional search:• jQuery(“p.description”) -> all “p” elements with a class description

• .last / .first / :contains(“…”) / etc.

Classes:• .addClass -> adds a class (not replace of the entire attribute)

• .removeClass

• .toggleClass -> if the class found it will be removed, otherwise if will be added

27

Page 28: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - jQuery

instead of writing jQuery you can write $

Effects (with animations!):• .hide() / .fadeout() / .slide()

Events:• $(“selector”).click = function {

this.something something…}

• this will refer to the current element that called the function

28

Page 29: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

JavaScript - jQuery

Setup should be called from:• $(document).ready -> same as window.onload

Tip: to parse a server response into JSON object use:• jQuery.parseJSON (“…”)

• Make sure the response is well formatted

References:• http://jquery.com/

• http://xhtml.co.il/he/jQuery

• http://try.jquery.com

• http://www.bramstein.com/projects/jlayout/

29

Page 30: © Liron Blecher JavaScript Liron Blecher. Agenda JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library

DEMO

jquery

30