Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli

Javascript, Appunti di Elementi di Informatica

javascript

Tipologia: Appunti

2015/2016
In offerta
30 Punti
Discount

Offerta a tempo limitato


Caricato il 15/09/2016

daniele.pastorino
daniele.pastorino 🇮🇹

4

(1)

2 documenti

Anteprima parziale del testo

Scarica Javascript e più Appunti in PDF di Elementi di Informatica solo su Docsity! JAVASCRIPT La web usability è una progettazione per rendere i siti web facili da usare per gli utenti senza che questi abbiamo competenze specifiche. Per valutare l’usabilità sono state create le dieci euristiche di Nielsen: 1. Visibilità dello stato di sistema (es. load) 2. Corrispondenza tra mondo reale e il sistema (es. parlare il linguaggio dell’utente) 3. Libertà e controllo dell’utente (es. evitare procedure lunghe) 4. Consistenza e standard 5. Prevenzione errori (es. no situazioni ambigue) 6. Riconoscimento anzi che ricordo 7. Flessibilità/efficienza 8. Estetica e design minimali (es. contenuto informativo più importante dell’estetica) 9. Aiuti di riconoscimento e risoluzione degli errori 10. Aiuti e documentazione Le informazioni devono essere il più chiaro e preciso possibile per eliminare ogni tipo di ambiguità. Le informazioni più importanti devono essere nella giusta posizione al’interno della pagina. Architettura dell’informazione disciplina che permette di organizzare i contenuti in modo semplice e intuitivo per l’utente. INTRODUZIONE ALLA PROGRAMMAZIONE I computer sono programmabili e svolgono compiti in base alle istruzioni che ricevono. Il calcolatore conosce il LINGUAGGIO MACCHINA che è basato su un ALFABETO BINARIO (0/1). Per facilitare l’interazione con l’utente nascono i LINGUAGGI DI PROGRAMMAZIONE che sono di “alto livello”, hanno una sintassi semplice e vicina al linguaggio dell’uomo. Codice sorgente programma scritto dal programmatore che può essere tradotto in linguaggio macchina con due tecniche: 1. Compilazione traduce velocemente ma non è eseguibile su due macchiane diverse 2. Interpretazione ogni volta prima di eseguire traduce, ma si può usare su più macchine (javascript) Algoritmo insieme ordinato di operazioni che descrivono i dati che devono essere utilizzati e determinano la sequenza di azioni elementari che devono essere svolte per risolvere no o più problemi. INTRODUZIONE A JAVASCRIPT Javascript è un linguaggio di scripting orientato agli oggetti e ha due estensioni: lato client e lato server. Per quanto riguarda il lato client, l’interprete di javascript è incorporato del broswer. Javascript interagisce con il HTML attraverso il DOM (Document Object Model) che è una forma di rappresentazione del documento e attraverso il quale si può accedere per modificare i dati del documento HTML. Ha una struttura ad albero. L’oggetto DOCUMENT è quindi molto importante perché è quello che contiene tutti gli altri elementi e identifica una pagina web. Per recuperare gli elementi all’interno di una pagina il DOM ci fornisce due metodi: 1. document.getElementById(id) (es. document.getElementByIid(“demo”)) 2. document.getElementByTagName(tagName). Il tag <script> </script> che contiene il codice javascript può essere inserito all’interni della <head> o all’interno del <body>. LE VARIABILI Le variabili contengono dei dati. Example var x = 5; var y = 6; var z = x + y; From the example above, you can expect: • x stores the value 5 • y stores the value 6 • z stores the value 11 Much Like Algebra In this example, price1, price2, and total, are variables: Example 2.dati complessi JavaScript Arrays JavaScript arrays are written with square brackets. Array items are separated by commas. The following code declares (creates) an array called cars, containing three items (car names): Example var cars = ["Saab", "Volvo", "BMW"]; JavaScript Objects JavaScript objects are written with curly braces. Object properties are written as name:value pairs, separated by commas. Example var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; TYPEOF The typeof Operator You can use the JavaScript typeof operator to find the type of a JavaScript variable: Example typeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name:'John', age:34} // Returns object LE FUNZIONI Le funzioni sono molto importanti in Javascript. Sono un blocco di istruzioni al quale viene associato un identificatore. Si usano quando le istruzioni devono essere utilizzate più volte all’interno del programma, per non ripeterle. Una volta che una funzione viene dichiarata può essere richiamata quante volte si vuole. Solo quando viene chiamata viene effettivamente eseguita. Una funzione è formata da : 1. nome 2. parametri (non sempre) che sotituiscono le variabili su cui opera una funzione. I nomi che si danno ai parametri sono PARAMETI FORMALI e vengono sostituiti dai nomi effettivi cioè i PARAMETRI ATTUALI 3. istruzioni tra le { } es. function saluta ( ) { document.write(“ciao”); } saluta(); function saluta (nome) { document.write (“ciao” + nome); } Saluta(Chiara); IL VALORE RETURN Function Return When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller": Example Calculate the product of two numbers, and return the result: var x = myFunction(4, 3); // Function is called, return value will end up in x function myFunction(a, b) { return a * b; // Function returns the product of a and b } The result in x will be: 12 VARIABILI LOCALI E GLOBALI Le variabili possono essere locali o globali, le prime servono a dichiarare un valore che verrà conservato in memoria per l'utilizzo della funzione o della routine in cui viene dichiarata, le seconde, al contrario, vengono dichiarate all'inizio di un blocco di script e possono essere utilizzate da una molteplicità di funzioni e routine. Vediamo un esempio di variabile locale: function mia_funzione() { var miaVariabile = 123; alert(miaVariabile); } In questo caso la nostra variabile miaVariabile esiste solo all'interno della funzione. Vediamo adesso un esempio di variabile globale: var miaVariabile = 123; function mia_funzione() { alert(miaVariabile); } JAVASCRIPT OBJECTS Essendo javascript un linguaggio orientato agli oggetti che quindi permetto allo sviluppatore di manipolare i dati che oggetti, questi ultimi hanno delle caratteristiche: 1. dati, detti proprietà 2. funzionalità, dette metodi Objects are variables too. But objects can contain many values. This code assigns many values (Fiat, 500, white) to a variable named car: var car = {type:"Fiat", model:500, color:"white"}; Object Properties The name:values pairs (in JavaScript objects) are called properties. var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; Object Methods Methods are actions that can be performed on objects. Methods are stored in properties as function definitions. Event Description onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page The Math Object The Math object allows you to perform mathematical tasks. The Math object includes several mathematical methods. One common use of the Math object is to create a random number: Example Math.random(); // returns a random number <!DOCTYPE html> <html> <body> <p>Math.random() returns a random number between 0 and 1.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = Math.random(); } </script> </body> </html> Math.min() and Math.max() Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments: Example Math.min(0, 150, 30, 20, -8); // returns -8 Example Math.max(0, 150, 30, 20, -8); // returns 150 <!DOCTYPE html> <html> <body> <p>Math.min() returns the lowest value.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = Math.min(0, 150, 30, 20, -8); } </script> </body> </html> JAVASCRIPT ARRAY Un ARRAY è un oggetto complesso che permette di memorizzare all’interno di una variabile un insieme di valori. p id="demo"></p> <script> var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> The first line (in the script) creates an array named cars. The second line "finds" the element with id="demo", and "displays" the array in the "innerHTML" of it. Array Properties and Methods The real strength of JavaScript arrays are the built-in array properties and methods: Examples var x = cars.length; // The length property returns the number of elements in cars var y = cars.sort(); // The sort() method sort cars in alphabetical order Array methods are covered in the next chapter. The length Property The length property of an array returns the length of an array (the number of array elements). Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // the length of fruits is 4 Adding Array Elements The easiest way to add a new element to an array is using the push method: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Lemon"); // adds a new element (Lemon) to fruits New element can also be added to an array using the length property: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits Se la variabile non ha nessuno dei valori sopra allora esegui le istruzioni e poi fermati var saluto; var nazione = prompt ("inserisci il nome di una nazione“, “”); switch (nazione) { case "Francia": saluto = "Bonjour!"; break; case "Italia": saluto = "Salve!"; break; case "Spagna": saluto = "Buenos Dias!"; break; default: saluto = "Spiacente! non conosco la tua lingua"; } alert(saluto); The While Loop The while loop loops through a block of code as long as a specified condition is true. Syntax while (condition) { code block to be executed } Example In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10: Example while (i < 10) { text += "The number is " + i; i++; } IL DOM DOCUMENT OBJECT MODEL, è un modo diverse di visualizzare il documento. È un’interfaccia che permette ai programmi di script di accedere dinamicamento e di modificare lo stile il contenuto e la struttura di un documento HTML. Tutti gli oggetti di un pagina fanno parte dell’OGGETO DOCUMENT. per invocare metodi e proprietà di document è necessario utilizzare la seguente sintassi: 1. document.metodo() (es. document.write(...)) 2.document.proprietà (es. document.title). Accedere agli elementi del DOM Attraverso l'ID di un elemento (metodo più usato): document.getElementById(id) Es. var y=document.getElementById(“titolo”); F 0 9 7ATTENZIONE! L'elemento viene memorizzato nella variabile come un oggetto F 0 9 7Attraverso il suo tag html: document.getElementsByTagName(tag) Es. var y=document.getElementsByTagName(p); Attraverso il nome della classe: document.getElementsByClassName(class) Es. var y=document.getElementsByClassName(“par”); ATTENZIONE! In un documento possono esserci più valori che condividono lo stesso tag o classe Attraverso il suo elemento html: document.anchors document.forms document.images document.links. Per “recuperare” o modificare il contenuto di un elemento si usa la proprietà innerHTML. Recupero valori Es. var y =document.getElementById(“titolo”); document.write (y.innerHTML) Es. var x = document.getElementsByTagName(“p”); document.write(x [0].innerHTML) Inserimento valori Es. document.getElementById(“titolo”).innerHTML=”Bla bla”; document.getElementsByTagName(“p”)[0].innerHTML=”Bla bla” F 0 9 7Modificare gli attributi Modificare gli attributi La sintassi per modificare il valore degli attributi è la seguente: document.getElementById(id).attributo = nuovo valore Es. <img id=”immagine” src=”fiore.jpg”> <script> document.getElementById(“immagine”).src=”luna.jpg” </script> F 0 9 7Modificare lo stile Modificare lo stile La sintassi per modificare lo stile di un elmento html è la seguente: document.getElementById(id).style.proprietà = nuovo valore Es. <p id=”paragrafo” > ….. </p> <script> document.getElementById(“paragrafo”).style.color=”blu e” </script> JQUERY $(document).ready(function(){ $("button").click(function(){ $(".test").hide(); }); }); Commonly Used jQuery Event Methods $(document).ready() The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter. click() The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element. The following example says: When a click event fires on a <p> element; hide the current <p> element: Example $("p").click(function(){ $(this).hide(); }); dblclick() The dblclick() method attaches an event handler function to an HTML element. The function is executed when the user double-clicks on the HTML element: Example $("p").dblclick(function(){ $(this).hide(); }); mouseenter() The mouseenter() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer enters the HTML element: Example $("#p1").mouseenter(function(){ alert("You entered p1!"); }); mouseleave() The mouseleave() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer leaves the HTML element: Example $("#p1").mouseleave(function(){ alert("Bye! You now leave p1!"); }); mousedown() The mousedown() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element: Example $("#p1").mousedown(function(){ alert("Mouse down over p1!"); }); mouseup() The mouseup() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is released, while the mouse is over the HTML element: Example $("#p1").mouseup(function(){ alert("Mouse up over p1!"); }); hover() The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element: Example $("#p1").hover(function(){ alert("You entered p1!"); }, function(){ alert("Bye! You now leave p1!"); }); focus() The focus() method attaches an event handler function to an HTML form field. The function is executed when the form field gets focus: Example $("input").focus(function(){ $(this).css("background-color", "#cccccc"); }); blur() The blur() method attaches an event handler function to an HTML form field. The function is executed when the form field loses focus: Example $("input").blur(function(){ $(this).css("background-color", "#ffffff"); }); The on() Method The on() method attaches one or more event handlers for the selected elements. Attach a click event to a <p> element: Example $("p").on("click", function(){ $(this).hide(); }); Attach multiple event handlers to a <p> element: Example $("p").on({ mouseenter: function(){ $(this).css("background-color", "lightgray"); }, mouseleave: function(){ jQuery has the following fade methods: • fadeIn() • fadeOut() • fadeToggle() • fadeTo() jQuery fadeIn() Method The jQuery fadeIn() method is used to fade in a hidden element. Syntax: $(selector).fadeIn(speed,callback); The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeIn() method with different parameters: Example $("button").click(function(){ $("#div1").fadeIn(); $("#div2").fadeIn("slow"); $("#div3").fadeIn(3000); }); jQuery fadeOut() Method The jQuery fadeOut() method is used to fade out a visible element. Syntax: $(selector).fadeOut(speed,callback); The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeOut() method with different parameters: Example $("button").click(function(){ $("#div1").fadeOut(); $("#div2").fadeOut("slow"); $("#div3").fadeOut(3000); }) jQuery fadeToggle() Method The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods. If the elements are faded out, fadeToggle() will fade them in. If the elements are faded in, fadeToggle() will fade them out. Syntax: $(selector).fadeToggle(speed,callback); The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeToggle() method with different parameters: Example $("button").click(function(){ $("#div1").fadeToggle(); $("#div2").fadeToggle("slow"); $("#div3").fadeToggle(3000); }); jQuery fadeTo() Method The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1). Syntax: $(selector).fadeTo(speed,opacity,callback); The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1). The optional callback parameter is a function to be executed after the function completes. The following example demonstrates the fadeTo() method with different parameters: Example $("button").click(function(){ $("#div1").fadeTo("slow", 0.15); $("#div2").fadeTo("slow", 0.4); $("#div3").fadeTo("slow", 0.7); }); jQuery Animations - The animate() Method The jQuery animate() method is used to create custom animations. Syntax: $(selector).animate({params},speed,callback); The required params parameter defines the CSS properties to be animated. The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the animation completes. The following example demonstrates a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 250px: Example $("button").click(function(){ $("div").animate({left: '250px'}); }); jQuery animate() - Manipulate Multiple Properties Notice that multiple properties can be animated at the same time: Example $("button").click(function(){ $("div").animate({ left: '250px', opacity: '0.5', height: '150px', width: '150px' }); }); jQuery animate() - Using Relative Values
Docsity logo


Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved