Java Script

Lets'go

OK:
<script>
// JavaScript goes here
</script>


<script src="http://www.mysite.com/MyCommonFunctions.js"></script>
Dans ce cas le browser met le code dans son cache et c'est réutilisable!

document = page html
document.bgColor = "red";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chapter 1, Example 3</title>
</head>
<body>
<p id="results"></p>
<script>
document.getElementById("results").innerHTML = "Hello World!";
</script>
</body>
popups: 
alert("Second Script Block");
<script>
console.log(5 + 6+" F12");
</script>

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 + "<br/>");

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] + "<br/>");
document.write("Age : " + personnel[1][1] + "<br/>");

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<br />");
}


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("<br />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 + "<br />");
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) + "<br />");
document.write(parseInt(myNumber, 10));

var myNumber = 44.5;
document.write(Math.round(myNumber) + "<br />");
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 + "<br />”);
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;
}
};



<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5, Example 8</title>
</head>
<body>
<script>
function createPerson(firstName, lastName) {
  return {
   firstName: firstName,
   lastName: lastName,
   getFullName: function() {
    return this.firstName + " " + this.lastName
   },
   greet: function(person) {
    alert("Hello, " + person.getFullName() +". I'm " + this.getFullName());
   }
  };
}
var johnDoe = createPerson("John", "Doe");
var janeDoe = createPerson("Jane", "Doe");
johnDoe.greet(janeDoe);
</script>
</body>
</html>
// 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
<body>
<div id="output"></div>
<script>
function updateTime() {
document.getElementById("output").innerHTML = new Date();
}
setInterval(updateTime, 1000);
</script>
</body>

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
<script>
var colorDepth = window.screen.colorDepth;
switch (colorDepth) {
case 1:
case 4:
document.bgColor = "white";
break;
case 8:
case 15:
case 16:
document.bgColor = "blue";
break;
case 24:

case 32:
document.bgColor = "skyblue";
break;
default:
document.bgColor = "white";
}
document.write("Your screen supports " + colorDepth +
"bit color");
</script>
 
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 8, Example 3</title>
</head>
<body>
<img src="" width="200" height="150" alt="My Image" />
<script>
var myImages = [
"usa.gif",
"canada.gif",
"jamaica.gif",
"mexico.gif"
];
var imgIndex = prompt("Enter a number from 0 to 3", "");
document.images[0].src = myImages[imgIndex];
</script>
</body>
</html>
 
 
 
if (typeof navigator.geolocation != "undefined") {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("This page uses geolocation, and your " +
"browser doesn't support it.");
}
</script>

Browser detection (sniffing)

<script>
function getBrowserName() {
var lsBrowser = navigator.userAgent;
if (lsBrowser.indexOf("MSIE") >= 0) {
return "MSIE";
} else if (lsBrowser.indexOf("Firefox") >= 0) {
return "Firefox";
} else if (lsBrowser.indexOf("Chrome") >= 0) {
return "Chrome";
} else if (lsBrowser.indexOf("Safari") >= 0) {
return "Safari";
} else if (lsBrowser.indexOf("Opera") >= 0) {
return "Opera";
} else {
return "UNKNOWN";
}
}

function getBrowserVersion() {
var ua = navigator.userAgent;
var browser = getBrowserName();
var findIndex = ua.indexOf(browser) + browser.length + 1;
var browserVersion = parseFloat(
ua.substring(findIndex, findIndex + 3));
return browserVersion;
}
var browserName = getBrowserName();
var browserVersion = getBrowserVersion();
if (browserName == "MSIE") {
if (browserVersion < 9) {
document.write("Your version of IE is too old");
} else {
document.write("Your version of IE is fully supported");
}
} else if (browserName == "Firefox") {
document.write("Firefox is fully supported");
} else if (browserName == "Safari") {
document.write("Safari is fully supported");
} else if (browserName == "Chrome") {
document.write("Chrome is fully supported");
} else if (browserName == "Opera") {
document.write("Opera is fully supported");
} else {
document.write("Sorry this browser version is not supported");
}
</script>

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

<!DOCTYPE html>
<html lang="en">
<head>
<title>This is a test page</title>
</head>
<body>
<span>Below is a table</span>
<table>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
</tr>
</table>
<script>
var tdElement = document.getElementsByTagName("td").item(0);
tdElement.style.color = "red";
</script>
</body>
</html>

ou

<script>
var tdElements = document.getElementsByTagName("td");
var length = tdElements.length;
for (var i = 0; i < length; i++) {
tdElements[i].style.color = "red";
}
</script>

css selector

<script>
var firstSpan = document.querySelector(".sub-title span");
firstSpan.style.color = "red";
</script>

<script>
var spans = document.querySelectorAll(".sub-title span");
var length = spans.length;
for (var i = 0; i < length; i++) {
spans[i].style.color = "red";
}
</script>

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

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<h1 id="heading1">My Heading</h1>
<p id="paragraph1">This is some text in a paragraph</p>
<script>
var container = document.documentElement;
alert(container.tagName);
</script>
</body>
</html>

attributes

<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 9, Example 1</title>
</head>
<body>
<p id="paragraph1">This is some text.</p>
<script>
var pElement = document.getElementById("paragraph1");
pElement.setAttribute("align", "center");
alert(pElement.getAttribute("align"));
pElement.removeAttribute("align");
</script>
</body>
</html>

➤ Change each CSS property with the style property. ➤ Change the value of the element’s class attribute.

Positioning and Moving Content

<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 9, Example 5</title>
<style>
#divAdvert {
font: 12pt arial;
}
.new-style {
font-style: italic;
text-decoration: underline;
}
</style>
</head>
<body>
<div id="divAdvert">
Here is an advertisement.
</div>
<script>
var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "new-style";
</script>
</body>
</html>

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

<!DOCTYPE html>
<html lang="en">
<head>
<title>Connecting Events Using HTML Attributes</title>
</head>
<body>
<a href="somepage.html" onclick="return linkClick()">Click Me</a>
<script>
function linkClick() {
alert("You Clicked?");
return true;
}
</script>
</body>
</html>

return false;

function linkClick() {
alert("This link is going nowhere");
return false;
}

load unload events

<body onload="myOnLoadfunction()"onunload="myOnUnloadFunction()">

double click , mouse over avec event

<p ondblclick="handle(event)">Paragraph</p>
<span onmouseover="handle(event)">Special Text</span>
<h1 onclick="handle(event)">Heading 1</h1>
<script>
function handle(e) {
alert(e.type);
}
</script>

ajout du listener en javascript

<a id="someLink" href="somepage.html">
Click Me
</a>
<script>
function linkClick() {
alert("This link is going nowhere");
return false;
}
document.getElementById("someLink").onclick = linkClick;
</script>

listener moderne addEventListener/removeEventListener

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Chapter 10, Example 5</title>
</head>
<body>
   <a id="someLink" href="somepage.html">
   Click Me
   </a>
  <script>
     var link = document.getElementById("someLink");
     
     link.addEventListener("click", function (e) {
        alert("This link is going nowhere");
        e.preventDefault();
     });
   </script>
</body>
</html>


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

<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 11: Example 2</title>
</head>
<body>
<form action="" name="form1">
<input type="button" name="myButton" value="Button clicked 0 times" />
</form>
<script>
var myButton = document.form1.myButton;
var numberOfClicks = 0;
function myButtonClick() {
numberOfClicks++;
myButton.value = "Button clicked " + numberOfClicks + " times";
}
myButton.addEventListener("click", myButtonClick);
</script>
</body>
</html>

form saisie avec controles de champs (attention firefox et blur problem)

<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 11: Example 4</title>
</head>
<body>
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>
<script>
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
if (txtAge.value == "" || txtName.value == "") {
alert("Please complete all of the form");
if (txtName.value == "") {
txtName.focus();
} else {
txtAge.focus();
}
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener("blur", txtAgeBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
</script>
</body>
</html>

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

<audio>
</audio>

<video controls preload poster="bbb.jpg">
<source src="bbb.mp4" type="video/mp4" />
<source src="bbb.webm" type="video/webm" />
<a href="bbb.mp4">Download this video.</a>
</video>

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

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Audio</title>
</head>
<body>
	<button id="playAudio" >Play</button>
	<button id="moinsAudio" >-</button>
	<button id="plusAudio" >+</button>
	<div id="volume" ></div>
	<button id="playAudio2" >Miaou</button>
	<audio id="audio" preload ></audio>
	<audio id="audio2" preload ></audio>
	<script>
		var audio = document.getElementById("audio");
		audio.src = "MiamiVice.mp3";
		var audio2 = document.getElementById("audio2");
		audio2.src = "987.mp3";
		
		var playAudio = document.getElementById("playAudio");
		var playAudio2 = document.getElementById("playAudio2");
		var moinsAudio = document.getElementById("moinsAudio");
		var plusAudio = document.getElementById("plusAudio");
		var volume = document.getElementById("volume");
		volume.innerHTML = audio.volume*100;
		function moinsAudioClick(e)
		{
			audio.volume -= 0.1;
			volume.innerHTML = Math.floor(audio.volume*100);
		}
		function plusAudioClick(e)
		{
			audio.volume += 0.1;
			volume.innerHTML = Math.floor(audio.volume*100);
		}
		
		function playAudio2Click(e)
		{
			//audio2.load();
			audio2.currentTime = 0;
			audio2.play();
		}
		function playAudioClick(e)
		{
			var target = e.target;
			if (target.innerHTML == "Play")
			{
				//audio.load();
				audio.play();
				target.innerHTML = "Pause";
				audio.currentTime = 0;
			}
			else
			{
				target.innerHTML = "Play";
				audio.pause();
				
			}
		}
		
		playAudio.addEventListener( "click", playAudioClick);
		playAudio2.addEventListener( "click", playAudio2Click);
		moinsAudio.addEventListener( "click", moinsAudioClick);
		plusAudio.addEventListener( "click", plusAudioClick);
	</script>
</body>

jQuery

<script src="jquery-2.1.1.min.js"></script>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
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"
  });

<div id="content" class="class-one class-two">
My div with two CSS classes!
</div>
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 = $("<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);

M:/SanDiegoWWW/www/dokuwiki/data/pages/san.javascript/start.txt · Dernière modification: 2016/11/01 16:10 par admin
 
Sauf mention contraire, le contenu de ce wiki est placé sous la licence suivante : CC Attribution-Noncommercial 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki