This JavaScript™ Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under …Descripción completa
Descripción: Javascript presentation in Spanish
JavaScriptDescripción completa
Descripción completa
Contiene todo la infromacion referente a la programación de javascriptDescripción completa
JavaScriptDescrição completa
Introducere in JavaScriptFull description
Description : Cours de javascript par Cabaré
JavaScript nije Java. Toliko! Kada smo ovo razjasnili, možemo da pređemo na značajnije i važnije učenje, kao npr. kako da napravite dobre slajdere. Šalu na stranu, JavaScript je jedna imple…Full description
Test upload
JavaScript Freebitcoin
Resumen JavascriptDescripción completa
Descripción completa
javaDescrição completa
JavaScript alapjai
JavaScript Zbirka
Descripción completa
Notes for Web Designing & Development Developme nt on the basis of GGSIPU BCA BCA Syllabus
JAVASCRIPT NOTES
JavaScript is the scripting language languag e of the Web. JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScrip JavaSc riptt is the mos mostt popu popular lar scriptin scripting g lan langua guage ge on the int intern ernet, et, and wor works ks in all major browsers, such as Internet Eplorer, !irefo, "hrome, #pera, and Safari. JavaScript was invented by $rendan Eich at %etscape &with %avigator '.(), and has appeared in all browsers since *++. -he official standardiation was adopted by the E"/0 organiation &an industry standardiation association) in *++1. JavaScript has been around for several years now, in many different flavors. flavors. -he main benefit of Javascript is to add additional interaction between the website and its visitors with just a little etra work by the web developer. Javascript allows industrious web masters to get more out of their website than 2-/3 and "SS can provide. $y definition, JavaScript is a client4side scripting language. -his means the web surfer5s browser will be running the script. -he opposite of client4side is server4side, which occurs in a languag e like 626. 626 scripts are run by the web hosting server. -here are many uses &and abuses7) ab uses7) for the powerful JavaScript language. 2ere are a few things that you may or may not have seen in your web surfing days8 •
"locks
•
/ouse -railers &an animation that follows your mouse when you surf a site)
Notes for Web Designing & Development Developme nt on the basis of GGSIPU BCA BCA Syllabus
What is JavaScript? •
JavaScript was designed to add interactivity to 2-/3 pages
•
JavaScript is a scripting language
•
0 scripting language is a lightweight programming language
•
JavaScript is usually embedded directly into 2-/3 pages
•
JavaScript is an interpreted language &means that scripts eecute without preliminary compilation)
•
Everyone can use JavaScript without purchasing a license
What Can JavaScript do? •
JavaScript JavaScript gives HTM designers designers a progra!!ing progra!!ing too" # 2-/3 authors are normally not programmers, but JavaScript is a scripting language with a very simple synta7 0lmost anyone can put small >snippets> of code into their 2-/3 pages
•
JavaScript can react to events # 0 JavaScript can be set to eecute when something happens, like when a page has finished loading or when a user clicks on an 2-/3 element
•
JavaScript can read and $rite HTM e"e!ents # 0 JavaScript can read and change the content of an 2-/3 element
•
JavaScript can %e &sed to va"idate data # 0 JavaScript can be used to validate form data before it is submitted to a server. -his -his saves the server from etra processing
•
JavaScript can %e &sed to detect the visitor's %ro$ser 4 0 JavaScript can be used to dete detect ct the the visi visito tor5 r5ss brow browse serr, and 4 depe dependi nding ng on the the brow browse serr 4 load load anoth another er page page specifically designed for that browser
•
JavaScript can %e &sed to create coo(ies 4 0 JavaScript can be used to store and retrieve information on the visitor5s computer
Ho$ To Write Write JavaScript JavaScr ipt
*. =se the the script script tag to to tell the browser browser you you are using using JavaScript JavaScript..
#ur first step was to tell the browser we were using a script with the @scriptA tag. %et we set the type of script eDual to >tetCJavaScript>. ou ou may notice that doing this is similar to the way you specify "SS, which is >tetCcss>. %et, we added an optional 2-/3 comment that surrounds our JavaScript code. If a browser does not support JavaScript, it will not display our cod e in plain tet to the user7 -he comment co mment was ended with a >CC44A> because >CC> signifies a comment in JavaScript. We add that to prevent a browser from reading the end of the 2-/3 comment comment in as a piece of JavaScript code.
$avaS%ript o%ument'(rite o%ument'(rite -he final step of our script was to use a function called document.write, document.write, which writes a string into our 2-/3 document. document.write can document.write can be used to write tet, 2-/3, or a little of both. We passed passed the famous string of tet to the function to spell out >2ello World7> World7> which it printed to the screen.
Where to Pla%e $avaS%ript -here are three general areas that JavaScript can be placed for use in a webpage. • • •
Inside the head tag Within Within the body bo dy tag In an eternal file
Notes for Web Designing & Development Developme nt on the basis of GGSIPU BCA BCA Syllabus
An *+ample ,ea S%ript @htmlA @headA @script typeB>tetCJavaScript>A @744 function popup&) F alert&>2ello World>) G CC44A @CscriptA @CheadA @bodyA @input typeB>button> onclickB>popup&)> valueB>popup>A @CbodyA @ChtmlA
*+ternal $avaS%ript #iles importing an *+ternal $avaS%ript #ile #ile Importing an eternal file is relatively painless. !irst, the file you are importing must be v alid JavaScript, and on"* JavaScript. Second, the file must have the file etension >.js>. 3astly, you must know the location of the file. 3et us assume we have a file >myjs.js> that contains a one line 2ello World alert function. 0lso, 0lso, let us assume that the file is the same directory as the 2-/3 file we are going to code up. -o import the file you would do the following in your 2-/3 document. ,i"e !*-s.-s Contents+ function popup&) F alert&>2ello World>) G HTM / JavaScript Code+ @htmlA @headA @script srcB>myjs.js>A @CscriptA @CheadA @bodyA @input typeB>button> onclickB>popup&)> valueB>"lick /e7>A $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page -
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
@CbodyA @ChtmlA
JavaScript State!ents
JavaScript statements are >commands> to the browser. -he purpose of the statements is to tell the browser what to do. Se!ico"on 0 Semicolon separates JavaScript statements.
%ormally you add a semicolon at the end of each eecutable statement. =sing semicolons also makes it possible to write many statements on one line. JavaScript Code JavaScript code &or just JavaScript) is a seDuence of JavaScript statements.
Each statement is eecuted by the browser in the seDuence they are written JavaScript Code 1"oc(s JavaScript statements can be grouped together in blocks.
$locks start with a left curly bracket, and en d with a right curly bracket. -he purpose of a block is to make the seDuence of statements eecute together. 0n good eample of statements grouped together in blocks, are JavaScript 2&nctions . JavaScript is Case Sensitive JavaScript is case sensitive.
Watch your capitaliation closely when you write JavaScript statements8 White Space
JavaScript ignores etra spaces. ou can add white space to your script to make it more readable. -he following lines are eDuivalent8 var nameB>2ege>H var name B >2ege>H $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page .
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
JavaScript Operators
#perators in JavaScript are very similar to operators that appear in oth er programming languages. -he definition of an operator is a symbol that is used to perform an operation.
JavaScript Arith!etic Operator Chart Operator
Eng"ish
E3a!p"e
0ddition
'
4
Subtraction
4'
K
/ultiplication
LK?
C
9ivision
*L C ?
M
/odulus
? M *(
Modulus 4 may be a new operation to you, but it5s just a special wa y of saying >finding the remainderN
@bodyA @script typeB>tetCJavaScript>A @744 var two B ' var ten B *( var linebreak B >@br CA> document.write&>two plus ten B >) var result B two ten document.write&result) document.write&linebreak)
document.write&>ten K ten B >) result B ten K ten document.write&result) document.write&linebreak) document.write&>ten C two B >) $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page /
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
result B ten C two document.write&result) CC44A @CscriptA @CbodyA
Comparison 0perators "omparisons are used to check the relationship between variables andCor values. 0 single eDual sign sets a value while a double eDual sign &BB) compares two values. "omparison ope rators are used inside conditional statements and evaluate to either true or false.
Operator
Eng"ish
E3a!p"e
Res&"t
BB
EDual -o
BB y
false
7B
%ot EDual -o
7B y
true
@
3ess -han
@y
true
A
Ay
false
@B
3ess -han or EDual -o
@B y
true
AB
AB y
false
)ATA T5PES
9ata can come in many different forms, or what we term types Some programming languages are strongly typed languages. In these languages, whenever we use a piece of data we need to eplicitly state what sort of data we are dealing with, and use of that data must follow strict rules applicable to its type. !or eample, we can5t add a number and a word together. $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page 1
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
JavaScript, on the other hand, is a weakly typed language and a lot more forgiving about how we use different types of data. When we deal with data, we often don5t need to specify what type of data it isH JavaScript will work it out for itself. N&!erica" )ata %umerical data comes in two forms8 •
•
Whole numbers, such as *L, which are also known as integers. -hese numbers can be positive or negative and can span a very wide range8 O'L? to 'L?. !ractional numbers, such as *.'?, which are also known as floating-point numbers. 3ike integers, they can be positive or negative, and they also have a massive range.
Te3t )ata 0nother term for one or more characters of tet is a string . We tell JavaScript that tet is to be treated as tet and not as code simply by enclosing it inside Duote marks &>). ! or eample, >2ello World> and >0> are eamples of strings that JavaScript will recognie. ou can also use the single Duote marks &5) JavaScript has a lot of other special characters, which can5t be typed in but can be represented using the escape character in conjunction with other characters to create escape sequences. -he principle behind this is similar to that used in 2-/3. !or eample, more than one space in a row is ignored in 2-/3, so we represent a space by PnbspH. Similarly, in JavaScript there are instances where we can5t use a character directly but must use an escape seDuence. -he following table details some of the more useful escape seDuences8
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Q%%
%% is a headecimal number that identifies a character in the 3atin4* character set.
1oo"ean )ata -he use of yes or no, positive or negative, and true or false is commonplace in the >real> world. -he idea of true and false is also fundamental to digital computersH they don5t understand maybes, only true and false. In fact, the concept of >yes or no> is so useful it has its own data type in JavaScript8 the Boolean data type. -he $oolean type has two possible values8 true for yes and false for no.
Varia%"es7Storing )ata in Me!or* 9ata can be stored either permanently or temporarily. We will want to keep important data, such as the details of a person5s bank account, in a permanent store 2owever, there are other cases where we don5t want to permanently store data, but simply want to keep a temporary note of it. Each variable is given a name so that you can refer to it elsewhere in your code. -hese names must follow certain rules. )ec"aring Varia%"es and 8iving The! Va"&es $efore you can use a variable, you should declare its eistence to the computer using the var keyword. -his warns the computer that it needs to reserve some memory for your data to be stored in later. -o declare a new variable called my!irst:ariable you would write var my!irst:ariableH %ote that the semicolon at the end of the line is not part of the variable name, but instead is used to indicate to JavaScript the end of a statement. -his line is an eample of a JavaScript statement. #nce declared, a variable can be used to store any type of data.
E9AMPE
@scriptA var aB*(,bB'(H document.write&a >@brA> b)H @CscriptA
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
$avaS%ript 4ariable Naming Conventions When choosing a variable name, you must first be sure that you do not use any of the JavaScript reserved names 0nother good practice is choosing variable names that are descriptive of what the variable holds. If you have a variable that holds the sie of a shoe, then name it >shoeRsie> to make your JavaScript more readable. !inally, JavaScript variable names may not start with a numeral &(4+). -hese variable names would be illegal8 1lucky, ++bottlesofbeer, and ?acharm.
What5s a #un%tion6 0 function is a piece of code that sits dormant until it is referenced or called upon to do its >function>. In addition to controllable eecution, functions are also a great time saver for doing repetitive tasks. Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. -his benefit is also known as >code reusability>.
*+ample #un%tion in $avaS%ript 0 function that does not eecute when a page loads should be placed inside thehead of your 2-/3 document. "reating a function is really Duite easy. 0ll you have to do is tell the browser you5re making a function, give the function a name, and then write the JavaScript like normal.
Ho$ to )e2ine a ,&nction S*nta3 function functionname&) F some code G
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
HTM / JavaScript Code+ @htmlA @headA @script typeB>tetCjavascript>A @744 function popup&) F alert&>2ello World>) G CC44A @CscriptA @CheadA @bodyA @input typeB>button> onclickB>popup&)> valueB>popup>A @CbodyA @ChtmlA
Ca""ing a ,&nction $ith Arg&!ents When you call a function, you can pass along some values to it, these values are called arguments or parameters.
-hese arguments can be used inside the function. ou can send as many arguments as you like, separated by commas &,) my!unction&argument1,argument2)
9eclare the argument, as variables, when you declare the function8 function my!unction&var1,var2) F some code G -he variables and the arguments must be in the epected order. -he first variable is given the value of the first passed argument etc.
@scriptA function my!unction&name,job) F alert&>Welcome > name >, the > job)H G @CscriptA
)ecision Ma(ing7The i2 and s$itch State!ents 0ll programming languages allow you to make decisions, that is, they allow the program to follow a certain course of action depending on whether a particular condition is met. -his is what gives programming languages their intelligence. Conditiona" State!ents :ery often when you write code, you want to perform different actions for different decisions. ou can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements8 •
i2 state!ent 4 use this statement to eecute some code only if a specified condition is true
•
i2...e"se state!ent 4 use this statement to eecute some code if the condition is true and another code if the condition is false
•
i2...e"se i2....e"se state!ent 4 use this statement to select one of many blocks of code to be eecuted
•
s$itch state!ent 4 use this statement to select one of many blocks of code to be eecuted
JavaScript I2 State!ent S*nta3
-here are two major parts to an If Statement8 the conditional statement and the code to be eecuted.
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
-he conditional statement is a statement that will evaluate to be either -rue or !alse. -he most common type of conditional statement used checks to see if something eDuals a value. 0n eample would be checking if a date eDuals your birthday. @script typeB>tetCjavascript>A :ar my %um B 1H if&my%um BB 1)F document.write&>3ucky 17>)H G @CscriptA
JavaScript I2 State!ent+ E"se I2...e"se State!ent =se the if....else statement to eecute some code if a condition is true and another code if the condition is not true.
-he Else clause is eecuted when the conditional statement is False. @script typeB>tetCjavascript>A var my%um B *(H if&my%um BB 1)F document.write&>3ucky 17>)H GelseF document.write&>ou5re not very lucky today...>)H G @CscriptA
I2...e"se i2...e"se State!ent =se the if....else if...else statement to select one of several blocks of code to be eecuted. S*nta3 if &condition1) F code to e e!ecuted if condition1 is true G else if &condition2) F code to e e!ecuted if condition2 is true $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page )
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
G else F code to e e!ecuted if neither condition1 nor condition2 is true G
E3a!p"e If the time is less than *(8((, you will get a > greeting, if not, but the time is less than '(8((, you will get a > greeting, otherwise you will get a > greeting8
if &time@*() F B>H G else if &time@'() F B>H G else F B>H G -he result of ! will be8
-he switch statement is used to perform different action based on different conditions.
The JavaScript S$itch State!ent =se the switch statement to select one of many blocks of code to be eecuted. S*nta3 switch&n) F case *8 $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page -
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
e!ecute code loc" 1 breakH case '8 e!ecute code loc" 2 breakH default8 code to e e!ecuted if n is different from case 1 and 2 G -his is how it works8 !irst we have a single ep ression n &most often a variable), that is evaluated once. -he value of the epression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is eecuted . =se %rea( to prevent the code from running into the net case automatically. E3a!p"e 9isplay today5s weekday4name. %ote that SundayB(, /ondayB*, -uesdayB', etc8
var dayBnew 9ate&).get9ay&)H switch &day) F case (8 B>-oday it5s Sunday>H breakH case *8 B>-oday it5s /onday>H breakH case '8 B>-oday it5s -uesday>H breakH case ?8 B>-oday it5s Wednesday>H breakH case 8 B>-oday it5s -hursday>H breakH case L8 B>-oday it5s !riday>H breakH case 8 B>-oday it5s Saturday>H
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
breakH G -he result of ! will be8 -oday it5s -uesday
The default :e*$ord =se the default keyword to specify what to do if there is no match8 E3a!p"e If it is %#- Saturday or Sunday, then write a default message8
var dayBnew 9ate&).get9ay&)H switch &day) F case 8 B>-oday it5s Saturday>H breakH case (8 B>-oday it5s Sunday>H breakH default8 B>3ooking forward to the Weekend>H G -he result of ! will be8 3ooking forward to the Weekend
ooping7The 2or and $hi"e State!ents
#ooping means repeating a block of code while a condition is true. -his is achieved in JavaScript using two statements, the while statement and the for statement. -he JavaScript For #oop resembles the for loop you may have seen in many other programming languages. It is used when you need to do a set of operations many times, with an increment of some kind after each run through the block of code. $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page /
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
#ften when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost eDual lines in a script we can use loops to perform a task like this. In JavaScript, there are different kinds of loops8 •
2or 4 loops through a block of code a specified number of times
•
$hi"e 4 loops through a block of code while a specified condition is true
•
do...$hi"e 4 also loops through a block of code while a specified condition is true
•
2or...in 4 loops through the properties of an object
JavaScript ,or oop E3p"ained
-here are four important aspects of a JavaScript for loop8 *. -he counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped . i is the normal label for this counter variable and what we will be using. '. -he conditional statement. It is what decides whether the for loop continues eecuting or not. -his check usually includes the counter variable in some way. ?. -he counter variable is incremented after every loop in theincrement section of the for loop. . -he code that is eecuted for each loop through the for loop. -his may seem strange, but *4? all occur on the same line of code. -his is because the for loop is such a standardied programming practice that the designers felt they might as well save some space and clutter when creating the for loop.
S*nta3 for &varialeB startvalueHvariale@endvalueHvarialeBvarialeincrement ) F code to e e!ecuted G
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
E3a!p"e for &iB(H i@LH i) F B >-he number is > i >@br CA>H G The 1rea( State!ent -he break statement breaks the loop and continue eecuting the code that follows after the loop &if any). E3a!p"e for &iB(Hi@*(Hi) F if &iBB?) F breakH G B >-he number is > i >@br CA>H G
The Whi"e oop While 3oops eecute a block of code as long as a specified condition is true.
-he while loop loops through a block of code while a specified condition is true. -he while loop is an advanced programming techniDue that allows you to do something over and over while a conditional statement is true. 0lthough the general uses of the while loop are usually a bit comple.
-avaScript Whi"e oop E3p"ained
-here are two key parts to a JavaScript while loop8 *. -he conditional statement which must be $rue for the while loop%s code to be eecuted. '. -he while loop%s code that is contained in curly braces >F and G> will be eecuted if the condition is $rue.
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
When a while loop begins, the JavaScript interpreter checks if the condition statement is true. If it is, the code between the curly braces is eecuted. 0t the end of the code segment >G>, thewhile loop loops back to the condition statement and begins again. If the condition statement is always $rue, then you will never eit the while loop, so be ver* care2&" when using while loops7 S*nta3 while &variale@endvalue) F code to e e!ecuted G Note+ -he @ could be any comparing operator. E3a!p"e -he eample below defines a loop that starts with iB(. -he loop will continue to run as long as i is less than L. i will increase by * each time the loop runs8 E3a!p"e while &i@L) F B >-he number is > i >@br CA>H iH
G
The )o...Whi"e oop -he do...while loop is a variant of the while loop. -his loop will eecute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. S*nta3 do F code to e e!ecuted G while &variale@endvalue)H
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
E3a!p"e -he eample below uses a do...while loop. -he do...while loop will always be eecuted at least once, even if the condition is false, because the statements are eecuted before the condition is tested8 E3a!p"e do F B >-he number is > i >@br CA>H iH G while &i@L)H
Creating Single 8ine Comments -o create a single line comment in JavaScript, you place two slashes >CC> in front of the code or tet you wish to have the JavaScript interpreter ignore. When you place these two slashes, all tet to the right of them will be ignored, until the net line. -hese types of comments are great for commenting o ut single lines of code and writing small notes. JavaScript Code+ @script typeB>tetCjavascript>A @744 CC -his is a single line JavaScript comment
document.write&>I have comments in my JavaScript code7>)H CCdocument.write&>ou can5t see this7>)H CC44A @CscriptA )isp"a*+ I have comments in my JavaScript code7
Creating 9ulti:line Comments 0lthough a single line comment is Duite useful, it can sometimes be burdensome to use when disabling long segments of code or inserting long4winded co mments. !or this large comments you can use JavaScript5s multi4line comment that begins with CK and ends with KC.
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
JavaScript Code+ @script typeB>tetCjavascript>A @744 document.write&>I have multi4line comments7>)H CKdocument.write&>ou can5t see this7>)H document.write&>ou can5t see this7>)H document.write&>ou can5t see this7>)H document.write&>ou can5t see this7>)H document.write&>ou can5t see this7>)H document.write&>ou can5t see this7>)H document.write&>ou can5t see this7>)HKC CC44A @CscriptA )isp"a*+ I have multi4line comments7
JavaScript Arra*
0n array is a variable that can store many variables within it. /any programmers have seen arrays in other languages, and they aren5t that different in JavaScript. -he following points should always be remembered when using arrays in JavaScript8 •
-he array is a special type of variable.
•
:alues are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets. Eample8 my0rray'T B >2ello World>H
•
:alues in an array are accessed b y the array name and location of the value. Eample8 my0rray'TH
•
JavaScript has built4in functions for arrays, so check out these built4in array functions before writing the code yourself7
Creating a $avaS%ript Array "reating an array is slightly different from creating a normal variable. $ecause JavaScript has variables and properties associated with arrays, you have to use a special function to create a new $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page !
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
array. -his eample shows how you would create a simple array, store values to it, and access these values. JavaScript Code+ @script typeB>tetCjavascript>A
var my0rray B new 0rray&)H my0rray(T B >!ootball>H my0rray*T B >$aseball>H my0rray'T B >"ricket>H document.write&my0rray(T my0rray*T my0rray'T)H @CscriptA
JavaScript Pop&p 1o3es
JavaScript has three kind of popup boes8 0lert bo, "onfirm bo, and 6rompt bo.
A"ert 1o3 0n alert bo is often used if you want to make sure information comes through to the user. When to ;se Pop&ps < A"erts
JavaScript alerts are ideal for the following situations8 •
If you want to be absolutely sure they see a message before doing anything on the website.
•
ou would like to warn the user about something. !or eample >the following p age contains humor not suitable for those under the age of *.>
•
0n error has occurred and you want to inform the user of the problem.
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
•
When asking users for confirmation of some action. !or eample, if they have just agreed to sign over the deed to their house and you want to ask them again if they are absolutely positive they want to go through with this decision7
When an alert bo pops up, the user will have to click >#;> to proceed. S*nta3 alert&> somete!t >)H
E3a!p"e @79#"-6E htmlA @htmlA @headA @scriptA function my!unction&) F alert&>I am an alert bo7>)H @CscriptA @CheadA @bodyA
@input typeB>button> onclickB>my!unction&)> valueB>Show alert bo> CA @CbodyA @ChtmlA
Con2ir! 1o3 0 confirm bo is often used if you want the user to verify or accept something.
When a confirm bo pops up, the user will have to click either >#;> or >"ancel> to proceed. -he JavaScript confirm function is very similar to the JavaScript alert function. 0 small dialogue bo pops up and appears in front of the web page currently in focus. -he confirm bo is different from the alert bo. It supplies the user with a choiceH they can either press #; to confirm the popup5s message or they can press cancel and not agree to the popup5s reDuest. If the user clicks >#;>, the bo returns true. If the user clicks >"ancel>, the bo returns false. $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page !)
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
S*nta3 confirm&> somete!t >)H
E3a!p"e @htmlA @headA @script typeB>tetCjavascript>A function confirmation&) F var answer B confirm&>3eave the document>) if &answer)F alert&>$ye bye7>)
G elseF alert&>-hanks for sticking around7>) G G @CscriptA @CheadA @bodyA @formA @input typeB>button> onclickB>confirmation&)> valueB>3eave document>A @CformA @CbodyA @ChtmlA Pro!pt 1o3 0 prompt bo is often used if you want the user to input a value before entering a page.
When a prompt bo pops up, the user will have to click either >#;> or >"ancel> to proceed after entering an input value. If the user clicks >#;> the bo returns the input value. If the user clicks >"ancel> the bo returns null. S*nta3 prompt&> somete!t >,>defaultvalue>)H
E3a!p"e var nameBprompt&>6lease enter your name>,>2arry 6otter>)H if &name7Bnull PP name7B>>) $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page !-
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
F B>2ello > name >7 2ow are you todayU>H G
ine 1rea(s -o display line breaks inside a popup bo, use a back4slash followed by the character n. E3a!p"e alert&>2elloQn2ow are youU>)H
Events in JavaScript What is an Event? -he absolute coolest thing about JavaScript is its ability to h elp you create dynamic webpages that increase user interaction, making the visitor feel like the website is almost coming alive right before her eyes. JavaScript5s interaction with 2-/3 is handled through events that occur when the user or browser manipulates a page.When the page loads, that is an event. When the user clicks a button, that click, too, is an event. 0nother eample of events are like pressing any key, closing window, resiing window etc. 9evelopers can use these events to eecute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable to occur. Events are a part of the 9ocument #bject /odel &9#/) 3evel ? and every 2-/3 element have a certain set of events which can trigger JavaScript "ode.
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Events occur when something in particular happens. !or eample, the user clicking on the page, clicking on a hyperlink, or moving his mouse pointer over some tet all cause events to occur. 0nother eample, which is used Duite freDuently, is the load event for the page. -he building blocks of an interactive web page is the JavaScript event system. 0n event in JavaScript is something that happens with or on the webpage. 0 few eample of events8 •
0 mouse click
•
-he webpage loading
•
/ousing over a hot spot on the webpage, also known as hovering
•
Selecting an input bo in an 2-/3 form
•
0 keystroke
Reacting to Events 0 JavaScript can be eecuted when an event occurs, like when a user clicks on an 2-/3 element. onc"ic( Event +
-his is the most freDuently used event type which occurs when a user clicks mouse left button. ou can put your validation, warning etc against this event type. To e3ec&te code $hen a &ser c"ic(s on an e"e!ent= add JavaScript code to an HTM event attri%&te
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
The on!o&seover and on!o&seo&t Events -he onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an 2-/3 element. OnMouseOver, as the name suggests, will execute the code when the mouse passes over the link. The onMouseOver will execute a piece of code when the mouse moves away from the link. They are used in exactly the same way as onClick.
E9AMPE
@htmlA @headA @script typeB>tetCjavascript>A function popup&) F alert&>2ello World>) G @CscriptA@CheadA @input typeB>button> valueB>"lick /e7> onclickB>popup&)> onmouseoverB>> on/ouseoutB>popup&)>A@br CA @CbodyA@ChtmlA
The on"oad and on&n"oad Events -he onload and onunload events are triggered when the user enters or leaves the page.
-he onload event can be used to check the visitor5s browser type and browser version, and load the proper version of the web page based on the information. -he onload and onunload events can be used to deal with cookies. E3a!p"e @htmlA
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
@body onloadB>check"ookies&)>A @scriptA function check"ookies&) F if &navigator.cookieEnabledBBtrue) F alert&>"ookies are enabled>) G else F alert&>"ookies are not enabled>) G G@CscriptA @pA0n alert bo should tell you if your browser has enabled cookies or not.@CpA @CbodyA@ChtmlA
JavaScript O%-ects >Everything> in JavaScript is an #bject8 a String, a %umber, an 0rray, a 9ate.... 0n object is just a special kind of data, with properties and methods. 0n object is a set of variables, functions, etc., that encapsulate data and methods.-hey may have properties and methods
Properties and Methods 6roperties are the values associated with an object.
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
In the following eample we are using the length property of the String object to return the number of characters in a string8 @script typeB>tetCjavascript>A var ttB>2ello World7>H document.write&tt.length)H @CscriptA -he output of the code above will be8 *'
/ethods are the actions that can be performed on objects. In the following eample we are using the to=pper"ase&) method of the String object to display a tet in uppercase letters8 @script typeB>tetCjavascript>A var strB>2ello world7>H document.write&str.to=pper"ase&))H @CscriptA -he output of the code above will be8 2E33# W#V397 -he String object is used to manipulate a stored piece of tet.
O%-ects in Rea" i2e+ If a car is an object8
-he properties of the car include name, model, weight, color, etc. 0ll cars have these properties, but the values of those properties differ from car to car. -he !ethods of the car could be start&), drive&), brake&), etc. 0ll cars have these methods, but they are performed at different times. $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page !3
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Creating JavaScript O%-ects JavaScript has several built4in objects, like String, 9ate, 0rray, and more.
ou can also create your own objects.
-his eample creates an object, and adds four properties to it8 E3a!p"e person#bjBnew #bject&)H person#bj.firstnameB>John>H person#bj.lastnameB>9oe>H person#bj.ageBL(H person#bj.eyecolorB>blue>H
Using an Object's Properties 0ccessing the values contained in an object5s properties is very simple. We write the name of the variable containing &or referencing) our object, followed by a dot, and then the name of the object5s property.
!or eample, if we defined an 0rray object contained in the variable my0rray, we could access its length property using my0rray.length -his would give us the number of elements contained in the array. $ut what can we do with this property now that we have itU We can use this property as we would any other piece of data and store it in a variable var my:ariable B my0rray.lengthH or show it to the user alert&my0rray.length)H In some cases, we can even change the value of the property, such as my0rray.length B *'H $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page )7
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Calling an Object's Methods /ethods are very much like functions in that they can be used to perform useful tasks, such as getting the hours from a particular date or generating a random number for us. 0gain like functions, some methods return a value, such as the 9ate object5s get2ours&) method, while others perform a task, but return no data, such as the 0rray object5s sort&) method.
=sing the methods of an object is very similar to using properties in that you put the objec t5s variable name first, then a dot, and then the name of the method. !or eample, to sort the elements of an 0rray in the variable my0rray, you may use the following code8 my0rray.sort&)H Just like functions, you can pass parameters to some methods, where the parameters are placed between the parentheses following the method5s name. 2owever, whether or not a method takes parameters, we must still put parentheses after the method5s name, just as we did with functions. 0s a general rule, anywhere you can use a function, you can use a method of an object.
T*pes o2 O%-ect+ > String O%-ects 3ike most objects, String objects need to be created before they can be used. -o create a String object, we can write
var string* B new String&>2ello>)H var string' B new String&*'?)H var string? B new String&*'?.L)H 2owever, as we have seen, we can also declare a string primitive and use it as if it were a String object, letting JavaScript do the conversion to an object for us behind the scenes. !or eample var string* B >2ello>H
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
@pA"lick the button to replace >/icrosoft> with >W?Schools> in the paragraph below8@CpA @button onclickB>my!unction&)>A-ry it@CbuttonA @scriptA function my!unction&) F var strB>:isit /icrosoft>H var nBstr.replace&>/icrosoft>,>W?Schools>)H document.write&n)H G @CscriptA@CbodyA@ChtmlA The length Property -he length property simply returns the number of cha racters in the string. !or eample
var my%ame B new String&>6aul>)H document.write&my%ame.length)H will write the length of the string >6aul> &that is, ) to the page.
S&%string Method
var myString B >JavaScript>H var mySubString B myString.substring&(,)H alert&mySubString)H
The charAt() and charCodeAt() Methods—electing a ingle Character fro! a tring -he char0t&) method takes one parameter8 the inde position of the character you want in the string. It then returns that character. char0t&) treats the positions of the string characters as starting at (, so the first character is at inde (, the second at inde *, and so on.
!or eample, to find the last character in a string, we could use the code $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page )!
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
var myString B prompt&>Enter some tet>,>2ello World7>)H var the3ast"har B myString.char0t&myString.length 4 *)H document.write&>-he last character is > the3ast"har)H
-he char"ode0t&) method is similar in use to the char0t&) method, but instead of returning the character itself, it returns a number that represents the decimal character code in the =nicode character set for that character. Vecall that computers only understand numbersto the computer, all our strings are just number data. When we reDuest tet rather than numbers, the computer does a conversion based on its internal understanding of each number and provides the respective character. !or eample, to find the character code of the first character in a string, we could write var myString B prompt&>Enter some tet>,>2ello World7>)H var the!irst"har"ode B myString.char"ode0t&()H document.write&>-he first character code is > the!irst"har"ode)H -he inde#f&) and lastInde#f&) /ethods!inding a String Inside 0nother String @script languageB>JavaScript> typeB>tetCjavascript>A var myString B >2ello paul. 2ow are you 6aul>H var found0t6ositionH found0t6osition B myString.inde#f&>6aul>)H alert&found0t6osition)H @CscriptA The !atch@ Method -he match&) method is very similar to the search&) method, ecept that instead of returning the position where a match was found, it returns an array. Each element of the array contains the tet of each match that is found.
-he /ath object allows you to perform mathematical tasks. -he /ath object includes several mathematical constants and methods. S*nta3 2or &sing properties
var B/ath.6IH var yB/ath.sDrt&*)H Note+ /ath is not a constructor. 0ll properties and methods of /ath can be called by using /ath as an object without creating it.
Mathe!atica" Constants JavaScript provides eight mathematical constants that can be accessed from the /ath object. -hese are8 E, 6I, sDuare root of ', sDuare root of *C', natural log of ', natural log of *(, base4' log of E, and base4*( log of E.
ou may reference these constants from your JavaScript like this8 /ath.E /ath.6I /ath.SXV-' /ath.SXV-*R' /ath.3%' /ath.3%*( /ath.3#<'E /ath.3#<*(E Mathe!atica" Methods In addition to the mathematical constants that can be accessed from the /ath object there are also several methods available. $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page )-
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
-he 9ate object is used to work with dates and times. -he 9ate object is useful when you want to display a date or use a timestamp in some sort of calculation. In Java, you ca n either make a 9ate object by supplying the date of your choice, or you can let JavaScript create a 9ate object based on your visitor5s system clock. It is usually best to let JavaScript simply use the system clock. 8et the JavaScript Ti!e
-he 9ate object has been created, and now we have a variable that holds the current date7 -o get the information we need to print out, we have to utilie some or all of the following functions8 •
getTi!e@ 4 %umber of milliseconds since *C*C*+1( Z *'8(( 0/
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
•
getSeconds@ 4 %umber of seconds &(4L+)
•
getMin&tes@ 4 %umber of minutes &(4L+)
•
getHo&rs@ 4 %umber of hours &(4'?)
•
get)a*@ 4 9ay of the week&(4). ( B Sunday, ... , B Saturday
•
get)ate@ 4 9ay of the month &(4?*)
•
getMonth@ 4 %umber of month &(4**)
•
get,&""5ear@ 4 -he four digit year &*+1(4++++)
E3a!p"e
@script typeB>tetCjavascript>A var current-ime B new 9ate&) var month B current-ime.get/onth&) * var day B current-ime.get9ate&) var year B current-ime.get!ullear&) document.write&month >C> day >C> year) @CscriptA
@script typeB>tetCjavascript>A @744 var current-ime B new 9ate&) var hours B current-ime.get2ours&) var minutes B current-ime.get/inutes&) if &minutes @ *()F minutes B >(> minutes G document.write&hours >8> minutes > >) if&hours A **)F document.write&>6/>) G else F document.write&>0/>) G CC44A @CscriptA
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
@ The Windo$ O%-ect It is the fundamental object in the browser. -he $indo$ object is supported by all browsers. It represent the browsers window in which the document appears.
0ll global JavaScript objects, functions, and variables automatically become members of the window object.
@htmlA@headA@scriptA function openWin&) F myWindowBwindow.open&>http8CCwww.w?schools.com>,>Rblank>,>widthB'((,heightB*((>)H G function closeWin&) F myWindow.close&)H G @CscriptA@CheadA@bodyA @input typeB>button> valueB>#pen 5myWindow5> onclickB>openWin&)> CA @input typeB>button> valueB>"lose 5myWindow5> onclickB>closeWin&)> CA @CbodyA@ChtmlA
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
E3a!p"e 2or Windo$ Stat&s+
@htmlA@headA @scriptA window.Status B >2ello and Welcome>H @CscriptA@CheadA@ChtmlA
D@ The screen O%-ect -he screen object property of the window object contains a lot of information about the display capabilities of the client machine. Its properties include the height and width properties, which indicate the vertical and horiontal range of the screen in piels.
0nother property of the screen object, which we will be using in an eample later, is the color9epth property. -his tells us the number of bits used for colors on the client5s screen @ The doc&!ent O%-ect7The Page Itse"2 0long with the window object, the document object is probably one of the most important and commonly used objects
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
F@ ,or! O%-ect+
@htmlA@headA@scriptA function but"heck!ormRonclick&) F var my!orm B document.form*H if &my!orm.tt0ge.value BB >> [[ my!orm.tt%ame.value BB >>) F alert&>6lease complete all the form>)H if &my!orm.tt%ame.value BB >>) F
my!orm.tt%ame.focus&)H G
else F
my!orm.tt0ge.focus&)H G G
else F alert&>-hanks for completing the form > my!orm.tt%ame.value)H G $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page )3
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
G function tt0geRonblur&) F var tt0ge B document.form*.tt0geH if &is%a%&tt0ge.value) BB true) F alert&>6lease enter a valid age>)H
tt0ge.focus&)H
tt0ge.select&)H G
G function tt%ameRonchange&) F window.status B >2i > document.form*.tt%ame.valueH G @CscriptA @CheadA @bodyA @form nameBform*A 6lease enter the following details8 @pA %ame8 $y Savleen ;aur, 0ssistant 6rofessor II-/4J6, <
Page -7