Guida Javascript

« Older   Newer »
 
  Share  
.
  1.  
    .
    Avatar

    .:Divinità:.

    Group
    Precursore
    Posts
    26,519

    Status
    Anonymous
    JavaScript è un linguaggio di scripting orientato agli oggetti comunemente usato nei siti web. Fu originariamente sviluppato da Brendan Eich della Netscape Communications con il nome di Mocha e successivamente di LiveScript, ma in seguito è stato rinominato "JavaScript" ed è stato formalizzato con una sintassi più vicina a quella del linguaggio Java di Sun Microsystems. JavaScript è stato standardizzato per la prima volta tra il 1997 e il 1999 dalla ECMA con il nome ECMAScript. L'ultimo standard, del dicembre 1999, è ECMA-262 Edition 3, e corrisponde a JavaScript 1.5. È anche uno standard ISO. La caratteristica principale di JavaScript è quella di essere un linguaggio interpretato. Il codice quindi non viene compilato bensì c'è un interprete (in JavaScript lato client esso è incluso nel browser che si sta utilizzando) che esegue riga per riga, a tempo di esecuzione, quanto trascritto nello script. JavaScript presenta quindi tutte le caratteristiche di un normale linguaggio interpretato (e di conseguenza i suoi vantaggi e svantaggi) con una sintassi analoga a quella di un linguaggio compilato (essa è relativamente simile a quella del C, del C++ e del Java), quindi con la possibilità di utilizzare funzionalità tipiche dei linguaggi di programmazione ad alto livello (strutture di controllo, cicli, etc.) e con in più anche la potenzialità di definire strutture più complesse, vicine a quelle adottate nei normali linguaggi object oriented (creazione di prototipi, istanziazione di oggetti, costruttori). Il principale tag del linguaggio di script Javascript è il tag script. Un documento può presentare in più parti la definizione del tag SCRIPT. Dopo aver parlato in generale degli script, occorre passare alla pratica e vedere come inserirli nella pagina HTML. La spiegazione risulta abbastanza complessa soprattutto perché Javascript ormai si integra così bene in HTML da non avere più spazi definiti, ma è possibile trovarlo ovunque.

    L'HTML prevede un tag apposito per gli script, e tale tag é:

    SPOILER (click to view)
    <script><!--
    ...
    //--></script>


    Tali tag, possono essere in numero variabile, l'unica attenzione sta nel chiuderli ogni volta che vengono aperti.
    I browser ricevono le pagine HTML con tutto il contenuto, quando si incontra il tag <script> questo viene eseguito come tutti gli altri tag, dall'alto in basso, ma il suo contenuto è interpretato secondo un codice diverso: in tal modo se il browser comprende il codice, questo viene eseguito, e se si incontra un errore nell'esecuzione dello stesso i casi sono due:
    1. la pagina viene visualizzata, ma il codice errato non viene eseguito;
    2. se il codice genera un loop (cioé un ciclo infinito) la pagina resta bianca o è visualizzata parzialmente perché l'esecuzione dall'alto in basso del codice HTML è momentaneamente interrotta.
    Così come scritto, però, il tag <script> non è completo perché i linguaggi di scripting sono diversi, allora occorre mettere anche la specificazione del linguaggio ed è:


    SPOILER (click to view)
    <script Language="Javascript"><!--
    //--></script>


    Ciò potrebbe bastare, ma negli ultimi riferimenti, soprattutto da parte di Netscape, si consiglia vivamente di indicare anche la versione di Javascript che si adopera, soprattutto perché l'evoluzione del linguaggio è continua e non sempre assicura la compatibilità con i vecchi browser. In tal modo si occulta il codice ai browser che non possono gestire gli aggiornamenti del linguaggio (per le versioni di Javascript si faccia riferimento alla tabella nella lezione sulle versioni JavaScript). Alla luce di quanto detto, il precedente script può essere considerato valido per la versione 1.0 di Javascript, e quindi per tutti i browser, mentre uno script del genere:
    SPOILER (click to view)
    <script Language="Javascript1.2"><!--
    //--></script>


    diventa leggibile solo da Explorer 4.0 o da versioni piu recenti. Vi chiederete anche come fare a conoscere tutte le compatibilità: ebbene non c'è nessun programma che aiuti in ciò, occorre conoscerle a fondo oppure usare un metodo empirico: testare le pagine su diversi browser e segnalare le incompatibilità, se queste dipendono dalla versione di Javascript, mascherarle con l'indicazione della versione.

    Ecco alcuni codici per voi

    Accettare le condizioni di un form cliccando sulla casellina:
    CODICE
    <HTML>
    <HEAD>
    <SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">
    function submitit(){
    var accetto = document.profilo.casella.checked;
    if (accetto!=true){
    alert("Non hai accettato le condizioni.");
    return false;
    }
    return true;
    }
    </SCRIPT>
    </HEAD>
    <BODY>
    <CENTER><H1>Modulo di registrazione</H1>
    </CENTER>
    <FORM NAME="profilo" ACTION="altra.htm" method="post" ONSUBMIT="return submitit()">
    Accetta le condizioni: <INPUT TYPE="checkbox" NAME="casella">
    <BR>
    <INPUT TYPE="submit" VALUE="Invia" NAME="submit">
    <INPUT TYPE="reset" VALUE="Cancella" NAME="reset">
    </FORM>
    </BODY>
    </HTML>


    Album Fotografico:
    CODICE
    <script language="JavaScript">
    <!--
    var viewPix = new Array("1.jpg","images/2.jpg","http://www.enricomilano.it/images/3.jpg")
    var thisImage = 0
    function doPast() {
    if (document.images && thisImage > 0) {
    thisImage--
    document.myShow.src=viewPix[thisImage]
    }
    }
    function doAfter() {
    if (document.images && thisImage < 2) {
    thisImage++
    document.myShow.src=viewPix[thisImage]
    }
    }
    // -->
    </script>
    <div align="center">
    <img name="myShow" src="1.jpg"><br>
    <a href="javascript:doPast()">Precedente</a>
    <a href="javascript:doAfter()">Successivo</a>
    </div>


    Aprire una finestra all'uscita:
    CODICE
    <body onUnload="window.open('arrivederci.htm', 'nuova','scrollbars=0,resizable=0,height=120,width=170')">


    Aprire una finestra al centro dello schermo:
    CODICE
    <script>
    function aprialcentro(url, nome) {
    largo = 600;
    alto = 300;
    posA = Math.floor((screen.height - alto)/2);
    posL = Math.floor((screen.width - largo)/2);
    window.open(url, nome, "width=" + largo + ",height=" + alto + ",top =" + posA + ",left=" + posL);
    }
    </script>


    Avvertimento al passaggio del mouse:
    CODICE
    <a href="http://www.indirizzo.com" onMouseOver="window.alert('Quello che vuoi nella finestra','')">Testo qualunque</a>


    Inserire un calendario nel proprio sito:
    CODICE
    <SCRIPT LANGUAGE="JavaScript">

    <!-- This script and many more are available free online at -->
    <!-- The JavaScript Source!! http://javascript.internet.com -->

    <!-- Begin
    monthnames = new Array(
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December");
    var linkcount=0;
    function addlink(month, day, href) {
    var entry = new Array(3);
    entry[0] = month;
    entry[1] = day;
    entry[2] = href;
    this[linkcount++] = entry;
    }
    Array.prototype.addlink = addlink;
    linkdays = new Array();
    monthdays = new Array(12);
    monthdays[0]=31;
    monthdays[1]=28;
    monthdays[2]=31;
    monthdays[3]=30;
    monthdays[4]=31;
    monthdays[5]=30;
    monthdays[6]=31;
    monthdays[7]=31;
    monthdays[8]=30;
    monthdays[9]=31;
    monthdays[10]=30;
    monthdays[11]=31;
    todayDate=new Date();
    thisday=todayDate.getDay();
    thismonth=todayDate.getMonth();
    thisdate=todayDate.getDate();
    thisyear=todayDate.getYear();
    thisyear = thisyear % 100;
    thisyear = ((thisyear < 50) ? (2000 + thisyear) : (1900 + thisyear));
    if (((thisyear % 4 == 0)
    && !(thisyear % 100 == 0))
    ||(thisyear % 400 == 0)) monthdays[1]++;
    startspaces=thisdate;
    while (startspaces > 7) startspaces-=7;
    startspaces = thisday - startspaces + 1;
    if (startspaces < 0) startspaces+=7;
    document.write("<table border=2 bgcolor=white ");
    document.write("bordercolor=black><font color=black>");
    document.write("<tr><td colspan=7><center><strong>"
    + monthnames[thismonth] + " " + thisyear
    + "</strong></center></font></td></tr>");
    document.write("<tr>");
    document.write("<td align=center>Su</td>");
    document.write("<td align=center>M</td>");
    document.write("<td align=center>Tu</td>");
    document.write("<td align=center>W</td>");
    document.write("<td align=center>Th</td>");
    document.write("<td align=center>F</td>");
    document.write("<td align=center>Sa</td>");
    document.write("</tr>");
    document.write("<tr>");
    for (s=0;s<startspaces;s++) {
    document.write("<td> </td>");
    }
    count=1;
    while (count <= monthdays[thismonth]) {
    for (b = startspaces;b<7;b++) {
    linktrue=false;
    document.write("<td>");
    for (c=0;c<linkdays.length;c++) {
    if (linkdays[c] != null) {
    if ((linkdays[c][0]==thismonth + 1) && (linkdays[c][1]==count)) {
    document.write("<a href=\"" + linkdays[c][2] + "\">");
    linktrue=true;
    }
    }
    }
    if (count==thisdate) {
    document.write("<font color='FF0000'><strong>");
    }
    if (count <= monthdays[thismonth]) {
    document.write(count);
    }
    else {
    document.write(" ");
    }
    if (count==thisdate) {
    document.write("</strong></font>");
    }
    if (linktrue)
    document.write("</a>");
    document.write("</td>");
    count++;
    }
    document.write("</tr>");
    document.write("<tr>");
    startspaces=0;
    }
    document.write("</table></p>");
    // End -->
    </SCRIPT>


    Caricare una pagina una nuova finestra:
    CODICE
    <SCRIPT language=JavaScript>
    window.name = 'salve';
    window.open('salve.html','nuova','toolbar=no,location=no,directories=no, status=no,menubar=no,title=no,scrollbars=no,resizable=no,copyhistory=no,width=300,height=200');
    </SCRIPT>


    Casella con testo scorrevole:
    CODICE
    script language="javascript">
    <!--
    var bannerID=0
    function text(msg,ctrlwidth) {
    msg = " --- "+msg
    newmsg = msg
    while (newmsg.length < ctrlwidth) {
    newmsg += msg
    }
    document.write ('<FORM NAME="Scrolltext">');
    document.write ('<CENTER><INPUT NAME="text" VALUE= "'+newmsg+'" SIZE= '+ctrlwidth+' ></CENTER>');
    document.write ('</FORM>');
    var bannerID = null
    rollmsg()
    }
    function rollmsg() {
    NowMsg = document.Scrolltext.text.value
    NowMsg = NowMsg.substring(1,NowMsg.length)+NowMsg.substring(0,1)
    document.Scrolltext.text.value = NowMsg
    bannerID = setTimeout("rollmsg()",100)//change the number 100 to represent the speed of the scroll. The larger the number the slower it moves
    }
    // -->
    </script>
    <script>
    <!--
    msg = " You can create any message that you want. Put it in here. and it will continue to scroll by for your visitors to see. That's all there is to it. "
    ctrlwidth = "75" //change this number to the length you would like the message box to be
    text(msg,ctrlwidth);
    // -->
    </script>

    In questo codice dove sta scritto:
    SPOILER (click to view)
    msg = "Qui scrivete il testo che volete che scorra mentre i visitatori guardano"
    ctrlwidth = "75" // Modificate questo numero se volete che la finestra di visualizzazione sia piu grande(msg,ctrlwidth);

    Contatore delle visite:
    CODICE
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var caution = false
    function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "")
    if (!caution || (name + "=" + escape(value)).length <= 4000)
    document.cookie = curCookie
    else
    if (confirm("Cookie exceeds 4KB and will be cut!"))
    document.cookie = curCookie
    }


    function getCookie(name) {
    var prefix = name + "="
    var cookieStartIndex = document.cookie.indexOf(prefix)
    if (cookieStartIndex == -1)
    return null
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
    if (cookieEndIndex == -1)
    cookieEndIndex = document.cookie.length
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
    }


    function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT"
    }
    }


    function fixDate(date) {
    var base = new Date(0)
    var skew = base.getTime()
    if (skew > 0)
    date.setTime(date.getTime() - skew)
    }

    var now = new Date()
    fixDate(now)
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000)
    var visits = getCookie("counter")
    if (!visits)
    visits = 1
    else
    visits = parseInt(visits) + 1
    setCookie("counter", visits, now)

    document.write("<CENTER><FONT FACE=VERDANA SIZE=2>Complimenti! Sei il <B>" + visits + "° </B>visitatore.</FONT></CENTER>")

    // -->
    </SCRIPT>

    Far suonare il Pc quando il mouse si sposta su un'oggetto:
    CODICE
    <html>
    <head>
    <script language="JavaScript">
    <!--

    var aySound = new Array();
    // Below: source for sound files to be preloaded
    aySound[0] = "laser.wav";

    // DO NOT edit below this line
    document.write('<BGSOUND ID="auIEContainer">')
    IE = (navigator.appVersion.indexOf("MSIE")!=-1 && document.all)? 1:0;
    NS = (navigator.appName=="Netscape" && navigator.plugins["LiveAudio"])? 1:0;
    ver4 = IE||NS? 1:0;
    onload=auPreload;

    function auPreload() {
    if (!ver4) return;
    if (NS) auEmb = new Layer(0,window);
    else {
    Str = "<DIV ID='auEmb' STYLE='position:absolute;'></DIV>";
    document.body.insertAdjacentHTML("BeforeEnd",Str);
    }
    var Str = '';
    for (i=0;i<aySound.length;i++)
    Str += "<EMBED SRC='"+aySound[i]+"' AUTOSTART='FALSE' HIDDEN='TRUE'>"
    if (IE) auEmb.innerHTML = Str;
    else {
    auEmb.document.open();
    auEmb.document.write(Str);
    auEmb.document.close();
    }
    auCon = IE? document.all.auIEContainer:auEmb;
    auCon.control = auCtrl;
    }
    function auCtrl(whSound,play) {
    if (IE) this.src = play? aySound[whSound]:'';
    else eval("this.document.embeds[whSound]." + (play? "play()":"stop()"))
    }
    function playSound(whSound) { if (window.auCon) auCon.control(whSound,true); }
    function stopSound(whSound) { if (window.auCon) auCon.control(whSound,false); }
    //-->

    </script>
    </head>
    <body>
    <A HREF="#" onMouseOver="playSound(0)" onMouseOut="stopSound(0)">Move mouse over to play sound</A>
    </body>
    </html>


    Pulsante che chiude la finestra sulla quale si Trova:
    CODICE
    <input type="button" value="Chiudi" onclick="javascript:window.close();">


    Salutate l'utente in base all'orario:
    CODICE
    <SCRIPT LANGUAGE=JavaScript>

    var today = new Date();

    var ora=today.getHours();
    document.write ("<FONT face=verdana size=3>")
    if (ora>00 && ora<12){
    document.write ("Buon giorno!")
    }
    if (ora>=12 && ora<=19){
    document.write ("Buon pomeriggio!")
    }

    if (ora>19 && ora<24){
    document.write ("Buona sera!")
    }
    document.write ("</FONT>")
    </SCRIPT>


    Scrivi con Javascript:
    CODICE
    <HTML>
    <HEAD>
    <TITLE></TITLE>
    <SCRIPT language=Javascript>
    function scrivi(){
    document.write("ciao!");
    return false;
    }
    </SCRIPT>
    </HEAD>
    <BODY>
    <script>scrivi qui()</script>
    </BODY>
    </HTML>


    Agggiunere hai preferiti:
    CODICE
    <a href="javascript:window.external.AddFavorite('http://www.tuolink.com/', 'My Site Title');">Aggiungi ai preferiti!</a>


    Un'orologio in JavaScript sempre ben aggiornato:
    CODICE
    <script type="text/javascript">
    var timer = null
    function stop()
    {
    clearTimeout(timer)
    }
    function start()
    {
    var time = new Date()
    var hours = time.getHours()
    var minutes = time.getMinutes()
    minutes=((minutes < 10) ? "0" : "") + minutes
    var seconds = time.getSeconds()
    seconds=((seconds < 10) ? "0" : "") + seconds
    var clock = hours + ":" + minutes + ":" + seconds
    document.forms[0].display.value = clock
    timer = setTimeout("start()",1000)
    }
    </script>

    <body onload="start()" onunload="stop()">

    <form>
    <input type="text" name="display" size="7" style="background-color:#E8EFFA; color:#000000; font:bold 14px verdana;">
    </form>


    Visualizzare un testo scorrevole:
    CODICE
    <SCRIPT language=JavaScript1.2>

    var marqueewidth=350
    var marqueeheight=54
    var speed=6

    var marqueecontents='<IMG SRC="immagine.gif"align=middle hspace=10><B><font face="Arial"> Benvenuto in Pcarena</font></B>'

    if (document.all)
    document.write('<marquee scrollAmount='+speed+' style="width:'+marqueewidth+'">'+marqueecontents+'</marquee>')

    function regenerate(){
    window.location.reload()
    }
    function regenerate2(){
    if (document.layers){
    setTimeout("window.onresize=regenerate",450)
    intializemarquee()
    }
    }

    function intializemarquee(){
    document.cmarquee01.document.cmarquee02.document.write('<nobr>'+marqueecontents+'</nobr>')
    document.cmarquee01.document.cmarquee02.document.close()
    thelength=document.cmarquee01.document.cmarquee02.document.width
    scrollit()
    }

    function scrollit(){
    if (document.cmarquee01.document.cmarquee02.left>=thelength*(-1)){
    document.cmarquee01.document.cmarquee02.left-=speed
    setTimeout("scrollit()",100)
    }
    else{
    document.cmarquee01.document.cmarquee02.left=marqueewidth
    scrollit()
    }
    }

    window.onload=regenerate2
    </SCRIPT>
     
    Top
    .
0 replies since 22/2/2011, 17:37   5 views
  Share  
.