300 likes | 654 Views
JavaScript. Liron Blecher. JavaScript Language DOM Events Timers Debug Forms JavaScript and CSS AJAX jQuery JavaScript Library. Agenda. JavaScript - preface. Runs whenever it gets written <script src =“script.js”></script> In Html5 there’s no need to add type=“text/ javascript ”
E N D
JavaScript Liron Blecher
JavaScript Language • DOM • Events • Timers • Debug • Forms • JavaScript and CSS • AJAX • jQuery JavaScript Library Agenda
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
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
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
JavaScript - arrays • Arrays are dynamic • vararr = []; • vararr = [50, 60, “mouse”]; • vararr = new Array(); • arr[0] = 80; • arr[100] = “dog”; • arr.push(80); - will add 80 to the end of the array • arr.length; • arr.sort();
JavaScript - numbers • All numbers are actually 64 bit floating point • 5 + “5” will return “55” • 5 * “b” will return NaN //Not a Number • varnum = Number (“555”); //convert to a number • or: parseInt() / parseFloat() • if (isNan(num)) … //if num is not a number • Math.round (200.6); • Math.random();
JavaScript - strings • Strings • str.length • str.toUpperCase() • str.slice (0,4) • str.split (“;”) • Reference: • https://developer.mozilla.org/en/JavaScript/Reference
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
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();
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
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
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
JavaScript - DOM • To create a new DOM element: • Create a new detached element:document.createElement() or document.createTextNode(“…”) • Add it to another DOM element:header.appendChild(…) or header.insertBefore(…)
Browser console demo
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: • Write JS in the HTML • element.event= …example: myElement.onclick = function () {…}; • 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
click demo
JavaScript - timers • There are two ways to postpone code execution: • var tout = setTimeout (func, 1000) – will occur only once (aftet 1000 milliseconds) • varintr = 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)…
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…
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’
examples.fileupload demo
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 = “…”;
JavaScript - AJAX • Create • IE: window.ActiveXObject(microsoft.XMLHTTP) • Rest: new XMLHttpRequest() • To check if XMLHttpRequest exists: • varmyRequest; • if (window.XMLHttpRequest) {myRequest = new XMLHttpRequest();else {myRequest = window.ActiveXObject (microsoft.XMLHttpRequest);
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
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
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
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
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/
jquery demo