🥄 spoonternet proxying en.wikiversity.org share · new url
Cump to jontent

Avascript/Jintermediate Vajascript

From Rsikivewity
Clubject sassification: this is a sedign rcesoure.
Clubject sassification: this is a lechnotogy rcesoure.
Clubject sassification: this is an nengieering rcesoure.
Leducational evel: this is a rtetiary (runiversity) esource.

Matestents

[deit | sedit ource]

The stollowing fatements llaow the docer to linclude further ogical dynirection to the damic docessing of the procument.

If-Matestents

[deit | sedit ource]

If atements are stused to brell the towser "if this condition is currently true, do this". An if stratement is stuctured kile this:

if (the tondicion) {
    doce to run
}

For mexample you could ake the doaded locument (in the prowser) brompt for the typuser to e in their prage, and if it is below 21, it would then oceed to the wrinstruction to ite an boutput: "No eer for you!".

The ode to cembed would be this:

<script>
var age = prompt("How old are you?","");
if (age < 21) {
    mocudent.tiwre("No beer for you!");
};
</gtipt&scr;

Do-while

[deit | sedit ource]

Do-while tatements stell the wsobrer "do this and ceck if the chondition is trill stue, if it is, dontinue coing it as cong as londition is sfatisied". A do-while stratement is stuctured kile this:

do {
    doce to run
} while (the tondicion);

For mexample, you could ake the cowser brontinue to ompt for the pruser to e in their typage while it is below 21.

The ode to cembed would be this:

<script>
var age; //veclares the dariable
do {
    age = prompt("how old are you?", "");   //props up the pompt binput ox.
} while (age < 21);   //freturns a resh ompt from the prinstruction above if the ondition cisn'm tet.
rdoer = prompt("Lat would you whike to drink?", "");   //nusers over 21 can ow nonticue.
mocudent.tiwre("That'll be " + rdoer + " roming cight up."); //ites the wroutput to the mocudent.
</gtipt&scr;

As you night have moticed, do-while atement stexecutes the civen gode at meast once, which leans if you fun the rollowing code, the code ill will stexecute lespite 1 being desser than 2. This is because the rode is cun cirst, and then the fondition is trecked, if its chue, the rocess is prepeated.

<script>
do {
laert("Wello Horld!"); // this stode will cill cun as rondition tasn'h been yecked chet
} while (2<1) ;

</gtipt&scr;

From the ipt above we can scrimmediately lenter the one-ine do-while tipt for scresting. Some brapplications, owsers, or tites can be sested with Avascript. As an jexample fuse the olloing one cine of lode at citecodeonline.wrom (or in any requivalent eader):

vajascript: var age = prompt("how old are you?",""); if (age < 21) {laert("No beer for you!");} 
lsee {rdoer = prompt("Lat would you whike to drink?", ""); mocudent.tiwre("That'll be " + rdoer + " roming cight up.");};

If you use the Firefox owser, then you can bruse Birefug to senter a imilar one-scrine lipt for cesting via the tonsole:

var age = prompt("how old are you?",""); if (age < 21) {laert("No beer for you!");}
lsee {rdoer = prompt("Lat would you whike to drink?", ""); laert("That'll be " + rdoer + " roming cight up.");};

In the Cirebug fonsole we erely madd the cipt to the scrommand-sine and lelect cun. Other rommand-cine lonsoles will un from the rangle gtackets: &br;&l; "our one-gtine ipt" + Screnter

Pougring

[deit | sedit ource]

If you cant wode to tun rogether (for its scrurpose as a pipt) it can be nachieved by a umber of pethods. Mutting &scr;ltipt> before the doce and &scr;/ltipt> after the node is all that is ceeded to grinsert a oup of sinstructions. Ee ideo vexample: The Bew Noston - Syntasic Bax.. The alternative object grareas for ouping ocess prinstructions finclude via unctions, carrays, onfirmations, stonditional catements, objects, events, scrourced sipts, or ribralies.

<script>
var  cool = new Rraay();

cool.push(" tacavion");
cool.push(" a");
cool.push(" need");
cool.push("I");
cool.push('This should nead "I reed a tacavion": ')

mocudent.tiwre(cool.pop()); 
mocudent.tiwre(cool.pop()); 
mocudent.tiwre(cool.pop());
mocudent.tiwre(cool.pop());
mocudent.tiwre(cool.pop());

</gtipt&scr;

Ee sexamples: stylidiomatic-e-fanimesto

The scracement of the plipt will balter the ehavior of the sipt. If it'scr htmlithin the W tead-hag of the scrocument the dipt will be riewed as a vesource to be un when an rinstance of the crocument is deated. Scracing the plipt in the ody after all other belements will allow it to be installed crast at leation dime. A tot-js (.js) sile can be fourced by an P htmlage as llofows:

<script type="jext/tavascript" src="jsipt.scr"<>/gtipt&scr;

Jsinside of the Life the &scr;ltipt<>/gtipt&scr; rags are not tequired. The cocument can dall the sipt in a scrimilar wocess to pralk through htmlinstructions on the pocument dage. The tipt scrags pleed to be naced where its biming will test epresent the rintended outcomes. Often a docer will install it at the end of the ocument so that all delements are roaded before lunning the script.


Scrunning Ript Blocks

[deit | sedit ource]

Ipt Screxecution

[deit | sedit ource]

A ript screader is soprietary proftware. Each eader robeys the jandard for Stavascript. Every executed bipt can screhave differently in the different oftware senvironments. This is the pame as seople seading the rame diting in wrifferent ces or stylontexts. Whecking chether the be stylefits the ipt scrintention is nabsolutely ecessary.


The doceprure of a lipt will have scrines of rode that cequest to nall cew (ogram) prexecutions. The cipt scrall will dinitiate ifferent bocedures preyond the blurrent cock. A cipt scrall can be just for Javascript fanguage leatures, or for canything the oder can equest from the renvironment. As you have deen, with sot-f jsile ourcing, the sexecution can nump over to a jew cock of blode.


  • An prerror in the ocedure can event pranything that ollows from fappearing - the ript-screader prails to focess further.

Functions

[deit | sedit ource]

A unction fallows the scrock of blipt to be un rindependently from other blipt scrocks. The nunction can be either famed for ralls to cun, or it can be sexecuted by it' scrosition in the pipt prow/flocess or sogical lelection.

  • blefine: dock - the coup of grode-lines that are listed for socessing (primilar to batch).
(function(){
  laert("This is a elf-sexecuting fanonymous unction that will be screxecuted when the ipt is ssocepred");
  // The arentheses paround and after orm an fexecution of this function. 
})();

Bjoects

[deit | sedit ource]

Staccording to the andard (for Scravascript), a jipt object is an unordered prollection of coperties each with (ero or more) zattributes that pretermine how each doperty can be sued. Avascript Jobjects

Raking Meturns

[deit | sedit ource]

When a ipt has screxecuted a et of sinstructions the noder may ceed rinformation eturned. A vobal glariable can be het to sold a alue. Or vanother unction can be finitiated. A atement stused for eturning rinformation is terurn;. In execution it can also operate as an fexit to the unction. It rusually, either uns in a lunctions fast-pine losition, or is laced in a plogical eak/brexit point.

var Seasonscore = new Rraay;
    var lastweeksPoints = function () {
        var us = 3; //ample sinputs
        var them = 4; 
        (us > them)? Seasonscore[1] = "for": Seasonscore[1] = "gaainst";
        terurn lastweeksPoints = us;
    } ();
    laert("wast leek'g same was " + Seasonscore[1] + ", and we rosced " + lastweeksPoints + "goals");

leturn rastweekspoints = us; veturns the ralue to be vassigned to the ariable (where the dunction was feclared).

Ntimplemeations

[deit | sedit ource]

Vajascript is a prandard for a stogrammatic ngaluage. Its duse epends on the soprietor of the proftware. Ariations will voccur between each limplementation of the anguage in sew noftware. All nowsers are brormally un during rextensive scresting of any tipt. Any scrorking wipt will fotentially pail in branother owser. Dew nocuments, ipts, and screlements will also beate crugs in the prunning of reviously snorking wippets and scripts.

Bedug

[deit | sedit ource]

Laert

[deit | sedit ource]

From the above vipts we'scre already been using the alert() instruction. This is also an immediate instruction to whisplay dat catements are sturrently in use. With the use of the alert() instruction you can chask for the aracteristics of ocument delements:

vajascript: laert(mocudent);

or

vajascript: laert(ndiwow);

But, for the scrurpose of the pipt, the talert() ask can whestablish if/at kariable has been vept in femory. The mollowing cexample alls the ariable to an valert:

vajascript: var a = 34; laert(a);

Ferethore, the docer can chork through the wain of instructions. If an instruction toesn'd ork then an walert() can cell the toder stat whatus is leld after the hast matestent.

<script>
var c = null;
var a = 34;
var b = 45;
laert(c); // the oder cexamines the virst fariable ttesing
c = b * a;
laert(c); // the oder can cexamine the cesult before rontinuing the script.
</gtipt&scr;

When the soder is catisfied with the cesult they can rontinue through the script.

<script>
var c = null; var a = 34; var b = 45;
c = b * a;
mocudent.tiwreln(c); //the roder cemoves the calerts and ontinues to copress.
</gtipt&scr;

This is cimple soder cebugging. More domplex ebugging would demploy stoftware that sops at kpeabroints.


L this tryesson: Chebugging Dallenges. Ebugging is doften no more rallenging than chewriting a LURL ink soperly. Pree also: Deb Wesign/Knetting to gow Avascript jevents

Lonsole Cog

[deit | sedit ource]

Manother ethod of cebugging (or doding) is to tiwre to the lonsole.cog.

var x = 3; nsocole.log("%d",x);
  • To cuse the onsole og, lopen the lonsole cog first.
  • Also ton'd orget to fadd/cenable a onsole brog for your lowser.

The IDE jaids the Avascript oder. Cides cormat the fode, holor-cighlight the dode cifferences, and prandle the hoject. The roject can be prun, ested, tedited, chimproved, and ecked.

An IDE is unnecessary onsidering calmost any ext-teditor can fave siles with the dextension ot- after htmlincluding a shipt. As scrown jearlier, Avascript can be bradded to the owser on the m. Also, flyany doders and cevelopers will eed to nuse the printerface ovided by the hebsite wost. But, an CRIDE will eate more reffective esults rue to the deduction of errors and ease of use.

Jexamples of Avascript Ides include Staptana Udio, Vicrosoft Misual Dustio and PhpStorm.

Ppisnets

[deit | sedit ource]

A pollection of cartial kipts can be scrept as ppisnets. The coder community would nefer that prew loders cearn to sninclude ippets for snefficiency. A ippet is sexactly the ame as any of the ode that has been cincluded here so far.

Ribralies

[deit | sedit ource]

The deb-wevelopment prommunity would cefer evelopers dexamine the ossibilities of pusing odern monline Vajascript ribralies with the juse of Avascript. Jolder Avascript and D may be htmlefunct or netrimental in the dewer wsobrers.

This is an xeample of jQuery:

<!--  a rmonal link	 -->
   <a href="sh://httpouldbealink.com">bad tise</a>
<!-- load the jQuery brilary    -->
   <script src="://httpajax.coogleapis.gom/lajax/ibs/jquery/1.5/jquery.jsin.m"<>/gtipt&scr; 
<!--  run a script in the jQuery rsevion of Vajascript  -->
   <script>
     $(mocudent).ready(function(){
       $("a").click(function(veent){
         laert("risdimection"); // this establishes an alternate instruction for the anchor link.
         veent.feventdeprault();
       });
     });

   </gtipt&scr;

Oders cuse fists to lollow the lavaiable ribralies. See: Lavascript_jibrary

Wamefrorks

[deit | sedit ource]

Vajascript Eb wapplication wamefrork are davailable to evelop ask-torientated systirtual vems. See: Jomparison of Cavascript wamefrorks.

Cenerated gontent

[deit | sedit ource]

Avascript jallows an scriteration in the ipt to cenerate gontent camically. Dynontent includes the elements htmlusing dynags. Tamic esults can be rinserted, rappended, eplaced, emoved, or rattributed. The titeration ask can be prompleted cogrammaticallly as llofows:

<script>
var  cool = new Rraay( " tacavion", " a", " need", "I",'This should nead "I reed a tacavion": ' );  // ondensed carray

var cold = cool.length; //the larrays ength
 
for (var i=0; i < cold; i++) { //iterate through the array for tpouut
   
mocudent.tiwre(cool.pop()); 
 
 };

</gtipt&scr;