====== Java Script ====== ==== Lets'go ==== OK: Dans ce cas le browser met le code dans son cache et c'est réutilisable! document = page html document.bgColor = "red"; Chapter 1, Example 3

popups: alert("Second Script Block"); ==== variables ==== var myFirstVariable; myFirstVariable = "Hello"; alert(myFirstVariable); myFirstVariable = 54321; alert saisie: var degFahren = prompt(“Enter the degrees in Fahrenheit”,50); degCent = 5/9 * degFahren - 32; println ou cout: document.write(greetingString + " " + myName + "
"); var myString = "56.02"; var totoInt = parseInt(myString, 10); var totoFloat = parseFloat(myString); NaN si pas de conversion var myVar1 = isNaN("Hello"); // true
==== TABLEAUX - length - slice(begin) - slice(begin,end+1) - sort() - indexOf(var) - lastIndexOf(var) - every(fonction) - some(fonction) - filter(fonction) ==== var myArray = new Array(); // old way var myArray; myArray = []; // new way var myArray = ["Paul",345,"John",112,"Bob",99]; var myArray = []; myArray[0] = "Paul"; myArray[1] = 345; myArray[2] = "John"; myArray[3] = 112; myArray[4] = "Bob"; myArray[5] = 99; var personnel = []; personnel[0] = []; personnel[0][0] = "Name0"; personnel[0][1] = "Age0"; personnel[0][2] = "Address0"; personnel[1] = []; personnel[1][0] = "Name1"; personnel[1][1] = "Age1"; personnel[1][2] = "Address1"; personnel[2] = []; personnel[2][0] = "Name2"; personnel[2][1] = "Age2"; personnel[2][2] = "Address2"; document.write("Name : " + personnel[1][0] + "
"); document.write("Age : " + personnel[1][1] + "
"); myArray.length myArray.slice(begin); myArray.slice(begin,end+1);
every, some, filter, forEach //every var numbers = [ 1, 2, 3, 4, 5 ]; function isLessThan3(value, index, array) { var returnValue = false; if (value < 3) { returnValue = true; } return returnValue; } alert(numbers.every(isLessThan3)); if (numbers.some(isLessThan3)) { var result = numbers.filter(isLessThan3); alert("These numbers are less than 3: " + result); } var numbers = [ 1, 2, 3, 4, 5 ]; for (var i = 0; i < numbers.length; i++) { var result = numbers[i] * 2; alert(result); } var numbers = [ 1, 2, 3, 4, 5 ]; function doubleAndAlert(value, index, array) { var result = value * 2; alert(result); } numbers.forEach(doubleAndAlert); // Pas de valeur retournée...juste un parcours des valeurs var numbers = [ 1, 2, 3, 4, 5 ]; function doubleAndReturn(value, index, array) { var result = value * 2; return result; } var doubledNumbers = numbers.map(doubleAndReturn); // avec valeurs retournées alert("The doubled numbers are: " + doubledNumbers); ==== statements - instructions - if ==== var age = prompt("Enter age:", ""); var isOverSixty = parseInt(age, 10) > 60; document.write("Older than 60: " + isOverSixty); if (roomTemperature > 80) { roomTemperature = roomTemperature – 10; } if ( !(myAge >= 0 && myAge <= 10) ) { document.write("myAge is NOT between 0 and 10
"); } if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10"); } else if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ){ document.write("myAge is between 30 and 39 " + "or myAge is between 80 and 89"); } else { document.write("myAge is NOT between 0 and 10, " + "nor is it between 30 and 39, nor " + "is it between 80 and 89"); } var myName = "Paul"; if (myName == "Paul") { alert("myName is Paul"); }
==== switch ==== case 1: document.write("Too low!"); break; case 2: document.write("Too low!"); break; case 3: document.write("You guessed the secret number!"); break; case 4: document.write("Too high!"); break; var secretNumber = prompt("Pick a number between 1 and 5:", ""); secretNumber = parseInt(secretNumber, 10); switch (secretNumber) { case 1: case 2: document.write("Too low!"); break; case 3: document.write("You guessed the secret number!"); break; case 4: case 5: document.write("Too high!"); break; default: document.write("You did not enter a number between 1 and 5."); break; } document.write("
Execution continues here");
==== for - for in - while - do while - break - continue ==== var loopCounter; for (loopCounter = 1; loopCounter <= 3; loopCounter++) { // code } var myArray = ["Paul","Paula","Pauline"]; for (index in myArray ) { //some code } var degCent = 100; while (degCent != 100) { // some code } var userAge; do { userAge = prompt("Please enter your age","") } while (isNaN(userAge) == true); ==== function ==== function myNoParamFunction() { } function writeUserWelcome(userName){ document.write("Welcome to my website " + userName + "
"); document.write("Hope you enjoy it!"); } writeUserWelcome("Paul"); function convertToCentigrade(degFahren) { var degCent = 5 / 9 * (degFahren ‐ 32); return degCent; } // Passage de fonction fn function doSomething(fn) { fn("Hello, World"); } doSomething(alert);
==== string - chaine de caracteres ==== * indexOf * lastIndexOf * subst(start, length) * substring(begin,end+1) * toLowerCase() * toUpperCase() * .length * charAt(pos) * charCodeAt(pos) * fromCharCode(,,,,...) * trim() * concat(string) * split // + RegExp * replace // + RegExp * search(toto) // position + RegExp * match(toto) // array of found values + RegExp var string1 = new String("Hello"); var string2 = new String(123); var string3 = new String(123.456); var string1 = "Hello"; var myName = "Jeremy"; document.write(myName.length); var myString = "Hello Jeremy. How are you Jeremy"; var foundAtPosition = myString.indexOf("Jeremy"); alert(foundAtPosition); foundAtPosition = myString.lastIndexOf("Jeremy"); alert(foundAtPosition); First, notice the string value assigned to foundAtPosition = myString.indexOf("Wrox", foundAtPosition); var myString = "JavaScript"; var mySubString = myString.substring(0,4); var myString = String.fromCharCode(65,66,67); var myString = "Beginning JavaScript, Beginning Java, " + "Professional JavaScript"; alert(myString.search("Java"));// 10 var myString = "1997, 1998, 1999, 2000, 2000, 2001, 2002"; myMatchArray = myString.match("2000"); alert(myMatchArray.length); ==== math ==== var myNumber = -101; document.write(Math.abs(myNumber)); var max = Math.max(21,22); // result is 22 var min = Math.min(30.1, 30.2, 29.5, 12.78); // result is 30.1 var myNumber = 101.01; document.write(Math.ceil(myNumber) + "
"); document.write(parseInt(myNumber, 10)); var myNumber = 44.5; document.write(Math.round(myNumber) + "
"); myNumber = 44.49; document.write(Math.round(myNumber)); var rand = Math.random(); // 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2), var po = Math.pow(2,8); * toFixed(nombreDecimales) var itemCost = 9.99; var itemCostAfterTax = 9.99 * 1.075; document.write("Item cost is $" + itemCostAfterTax + "
”); itemCostAfterTax = itemCostAfterTax.toFixed(2); document.write("Item cost fixed to 2 decimal places is " +"$" + itemCostAfterTax);
==== date ==== var myDate = new Date(); var theDateSecondes = new Date(seconds); var theDateEasy = new Date(year, month, day, hours, minutes, seconds, milliseconds); // getDate() The day of the month // getDay() The day of the week as an integer, with Sunday as 0, Monday as 1, and so on // getMonth() The month as an integer, with January as 0, February as 1,and so on // getFullYear() The year as a four‐digit number // getHours() // getMinutes() // getSeconds() // getMilliseconds() // toTimeString() // toDateString() Returns the full date based on the current time zone as a human‐readable string, for example, “Wed 31 Dec 2003” // setDate() The date of the month is passed in as the parameter to set the date. // setMonth() The month of the year is passed in as an integer parameter, where 0 is January, 1 is February, and so on. // setFullYear() This sets the year to the four‐ // setHours() // setMinutes() // setSeconds() // setMilliseconds() var nowDate = new Date(); var currentDay = nowDate.getDate(); nowDate.setDate(currentDay + 28); ==== object - class ==== var johnDoe = new Object(); var johnDoe = {}; johnDoe.firstName = "John"; johnDoe.lastName = "Doe"; johnDoe.greet = function() { alert("My name is " + this.firstName + " " + this.lastName; }; johnDoe.greet(); var johnDoe = { firstName : "John", lastName : "Doe", greet : function() { alert("My name is " + this.firstName + " " + this.lastName; } }; Chapter 5, Example 8 // constructeur function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } Person.prototype.getFullName = function() { return this.firstName + " " + this.lastName; }; Person.prototype.greet = function(person) { alert("Hello, " + person.getFullName() +". I'm " + this.getFullName()); }; var johnDoe = new Person("John", "Doe"); ==== RegExp ==== Voir Beginning JavaScript (très bien fait) var myRegExp = /[a-z]/; var myRegExp = new RegExp("[a-z]"); var myRegExp = /\b/; var myRegExp = new RegExp("\\b"); ==== Timers ==== // un tir var timerId = setTimeout(yourFunction, millisecondsDelay) clearTimeout(timerId); // tirs réguliers var myTimerID = setInterval(myFunction,5000); clearInterval(myTimerID); // heure
==== Browser ==== browser object model (BOM) There is no standard BOM implementation (although some attempt is being made with the HTML5 specification). window contient location, history, document, navigator et screen document contient forms, images et links history.go(-2); history.go(3); history.back() ;// history.go(-1) ; history.forward() ; // history.go(1) ; location href, hostname, port and protocol location.replace("myPage.html"); // remplace la page courante par myPage.html location.href = "myPage.html"; // ajout à l’historique geolocation html5 : function success(position) { var crds = position.coords; var latitude = crds.latitude; var longitude = crds.longitude; var altitude = crds.altitude; var speed = crds.speed; } function geoError(errorObj) { alert("Uh oh, something went wrong"); //1 Failure occurred because the page did not have permission to acquire the position of the device/computer. //2 An internal error occurred. //3 The time allowed to retrieve the device’s/computer’s position was reached before the position was obtained. } navigator.geolocation.getCurrentPosition(success, geoError); window.screen.height window.screen.width window.screen.colorDepth Chapter 8, Example 3 My Image if (typeof navigator.geolocation != "undefined") { navigator.geolocation.getCurrentPosition(geoSuccess, geoError); } else { alert("This page uses geolocation, and your " + "browser doesn't support it."); } ==== Browser detection (sniffing) ==== What gives JavaScript this power over a web page is the document object model (DOM), a tree‐like representation of the web page. ==== DOM ==== id selector This is a test page Below is a table
Row 1 Cell 1 Row 1 Cell 2
ou
css selector element object Member Name Description tagName Gets the element’s tag name getAttribute() Gets the value of an attribute setAttribute() Sets an attribute with a specified value removeAttribute() Removes a specific attribute and its value from the element

My Heading

This is some text in a paragraph

attributes Chapter 9, Example 1

This is some text.

➤ Change each CSS property with the style property. ➤ Change the value of the element’s class attribute. Positioning and Moving Content Chapter 9, Example 5
Here is an advertisement.
var divAdvert = document.getElementById("divAdvert"); divAdvert.style.position = "absolute"; divAdvert.style.left = "100px"; // set the left position divAdvert.style.top = "100px"; // set the right position
onclick event Connecting Events Using HTML Attributes Click Me return false; function linkClick() { alert("This link is going nowhere"); return false; } load unload events double click , mouse over avec event

Paragraph

Special Text

Heading 1

ajout du listener en javascript Click Me listener moderne addEventListener/removeEventListener Chapter 10, Example 5 Click Me elementObj.removeEventListener("click", elementObjClick); 3 listeneres a la fois (pas possible avec l'ancienne methode) elementObj.addEventListener("click", handlerOne); elementObj.addEventListener("click", handlerTwo); elementObj.addEventListener("click", handlerThree); event.cancelable event.currentTarget event.target event.timestamp event.type MouseEvent altKey Indicates whether the Alt key was pressed when the event was generated button Indicates which button on the mouse was pressed clientX Indicates where in the browser window, in horizontal coordinates, the mouse pointer was when the event was generated clientY Indicates where in the browser window, in vertical coordinates, the mouse pointer was when the event was generated ctrlKey Indicates whether the Ctrl key was pressed when the event was generated metaKey Indicates whether the meta key was pressed when the event was generated relatedTarget Used to identify a secondary event target. For mouseover events, this property references the element at which the mouse pointer exited. For mouseout events, this property references the element at which the mouse pointer entered screenX Indicates the horizontal coordinates relative to the origin in the screen screenY Indicates the vertical coordinates relative to the origin in the screen shiftKey Indicates whether the Shift key was pressed when the event was generated click occurs when a mouse button is clicked (pressed and released) with the pointer over an element or text. ➤➤ mousedown occurs when a mouse button is pressed with the pointer over an element or text. ➤➤ mouseup occurs when a mouse button is released with the pointer over an element or text. ➤➤ mouseover occurs when a mouse button is moved onto an element or text. ➤➤ mousemove occurs when a mouse button is moved and it is already on top of an element or text. ➤➤ mouseout occurs when a mouse button is moved out and away from an element or text. document.addEventListener("mouseover", handleEvent); document.addEventListener("mouseout", handleEvent); document.addEventListener("click", handleEvent); KeyboardEvent altKey Indicates whether the Alt key was pressed when the event was generated charCode Used for the keypress event. The Unicode reference number of the key ctrlKey Indicates whether the Ctrl key was pressed when the event was generated keyCode A system‐ and browser‐dependent numerical code identifying the pressed key metaKey Indicates whether the meta key was pressed when the event was generated shiftKey Indicates whether the Shift key was pressed when the event was generated bouton Chapter 11: Example 2
form saisie avec controles de champs (attention firefox et blur problem) Chapter 11: Example 4
Please enter the following details:

Name:

Age:

JSON (Jason) var person = { firstName: "John", lastName: "Doe", age: 30 }; var json = JSON.stringify(person); var johnDoe = JSON.parse(json); var fullName = johnDoe.firstName + " " + johnDoe.lastName; cookies to web storage html 5 localStorage.setItem("userName", "Paul"); localStorage.userName = "Paul"; localStorage.setItem("user name", "Paul"); var name = localStorage.getItem("userName"); var name = localStorage.userName; localStorage.removeItem("userName"); localStorage.userName = null; localStorage.clear(); // no more key/value pairs localStorage.person = JSON.stringify(johnDoe); var savedPerson = JSON.parse(localStorage.person); Audio Video Html5 if (video.canPlayType("video/webm") == "probably") { video.src = "bbb.webm"; } else { video.src = "bbb.mp4"; canPlayType(mimeType) Determines the likelihood that the browser can play media of the provided MIME type and/or codec load() Begins to load the media from the server pause() Pauses the media playback play() Begins or continues the playback of the media autoplay Gets or sets the autoplay HTML attribute, indicating whether playback should automatically begin as soon as enough media is available controls Reflects the controls HTML attribute currentTime Gets the current playback time. Setting this property seeks the media to the new time. duration Gets the length of the media in seconds; zero if no media is available. Returns NaN if the duration cannot be determined ended Indicates whether the media element has ended playback loop Reflects the loop HTML attribute. Indicates whether the media element should start over when playback reaches the end muted Gets or sets whether the audio is muted paused Indicates whether the media is paused playbackRate Gets or sets the playback rate. 1.0 is normal speed. poster Gets or sets the poster HTML attribute preload Reflects the preload HTML element attribute src Gets or sets the src HTML attribute volume The audio volume. Valid values range from 0.0 (silent) to 1.0 (loudest). video.src = "new_media.mp4"; video.load(); video.play(); Audio mp3 Audio
jQuery var allParagraphs = $("p"); $("a, #myDiv, .myCssClass, p > span").attr("style", "color:red;"); $("#myDiv").css("color", "red"); var allParagraphs = $("p"); allParagraphs.css("background-color", "yellow"); // correct! allParagraphs.css("backgroundColor", "blue"); // correct, too! allParagraphs.css({ color: "blue", backgroundColor: "yellow" });
My div with two CSS classes!
var content = $("#content"); content.addClass("class-three"); content.addClass("class-four"); content.addClass("class-three").addClass("class-four"); content.removeClass("class-one"); var target = $(e.target); if (e.type == "mouseover" || e.type == "mouseout") { target.toggleClass("class-one"); } var a = $("").attr({ id: "myLink", href: "http://jquery.com", title: "jQuery's Website" }).text("Click here to go to jQuery's website"); $(document.body).append(a); function elementClick(e) { alert("You clicked me!"); } $(".class-one").on("click", elementClick); function eventHandler(e) { if (e.type == "click") { alert("You clicked me!"); } else { alert("You double-clicked me!"); } } $(".class-two").on("click dblclick", eventHandler); function clickHandler(e) { alert("You clicked me!"); } function dblclickHandler(e) { alert("You double-clicked me!"); } $(".class-three").on({ click: clickHandler, dblclick: dblclickHandler }); $(".class-one").off("click", elementClick); $(".class-two").off("click dblclick", eventHandler); $(".class-three").off({ click: clickHandler, dblclick: dblclickHandler }); $(".class-four").off(); function clickHandler(e) { e.preventDefault(); alert(e.target.tagName + " clicked was clicked."); } $(".class-two").on("click", clickHandler);