1 / 30

JavaScript

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 ”

kiara
Download Presentation

JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript Liron Blecher

  2. JavaScript Language • DOM • Events • Timers • Debug • Forms • JavaScript and CSS • AJAX • jQuery JavaScript Library Agenda

  3. 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

  4. 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

  5. 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

  6. 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();

  7. 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();

  8. JavaScript - strings • Strings • str.length • str.toUpperCase() • str.slice (0,4) • str.split (“;”) • Reference: • https://developer.mozilla.org/en/JavaScript/Reference

  9. 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

  10. 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();

  11. 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

  12. 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

  13. 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

  14. 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(…)

  15. Browser console demo

  16. 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);

  17. 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

  18. click demo

  19. 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)…

  20. 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…

  21. 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’

  22. examples.fileupload demo

  23. 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 = “…”;

  24. 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);

  25. 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

  26. 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

  27. 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

  28. 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

  29. 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/

  30. jquery demo

More Related