15a-JavaScript

advertisement
JavaScript
Liron Blecher
© 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
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
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
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
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
JavaScript - strings
Strings
• str.length
• str.toUpperCase()
• str.slice (0,4)
• str.split (“;”)
Reference:
• https://developer.mozilla.org/en/JavaScript/Reference
8
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
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
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
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
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
JavaScript - DOM
To create a new DOM element:
14
1.
Create a new detached element:
document.createElement() or
document.createTextNode(“…”)
2.
Add it to another DOM element:
header.appendChild(…) or header.insertBefore(…)
Browser console
DEMO
15
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:
16
1.
Write JS in the HTML
2.
element.event = …
example: myElement.onclick = function () {…};
3.
document.addEventListener (‘click’, func);
(in IE8: attachEvent(‘onclick’, func);
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
click
DEMO
18
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:
•
19
clearTimeout(tout) or clearInterval(intr)…
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
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
examples.fileupload
DEMO
22
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
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
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
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
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
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
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
jquery
DEMO
30
Download