0% found this document useful (0 votes)
21 views

Java Script

Uploaded by

Ishita Mahajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Script

Uploaded by

Ishita Mahajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

o c t 22

11/

JavaScript Built-In Functions eval()


script code
Folowing fns are used for explicit type it as if it was

conversions
executes
Evaluates a string and
eval) a numeric value
to
Converts a string expression
parselt) varx 10;
parseFloat() var y 20;
y")+ "<br>";
*

var a =
eval("x
"<br>":
var b eval("2 +2")+
=

"<br>";
varc eval("x + 17")+
Output
200

27

parselnt() parseFloat()
Parsesa string argument and returns an integer
F n returns the first
integer contained in string or 0 if the and returns a floating point
string does not begin with an integer. Parses a string argument
number.
var a parseint("10")+ "<br>";
Only the first number in the string is returned!
var c= parselnt("10.33")+ "<br»"; Leading and trailing spaces are allowed.
var d= parseint"34 45 66")+"<br>"; number,
var e parselnt(" 60 ") + "<br>";
the first character cannot be converted to a
IfparseFloat() returns NaN.
var f parseint("40 years") + "<br"; var c= parseFloat("1o.33")

Output var d parseFloat("34 45 66")


10 var e parseFloat(" 60 ")
10 varf parseFloat("40 years")
34 varg parseFloat("He was 40")
utp
40 10.33 34 60 40 NaN

JavaScript's DOM- Instance JavaScript Assisted Style sheets DOM


Hierarchy USSS DOM]
windo ISSSuse JavaScriptynta:tocontrol docunoent's presentasion style. When
a SSS embedded
a is ia an

HTML poge within the <HEAD. HEAD» ug thea the JavaScrigi DOM picks up whoie at nw
- Docunent of objects, which add to the stardard DOM objects already recognized by lavaacript The addiboal
- Anchor objects brought into the DOM by JSSS are shown in diagran
-Lik 1- Docunent
I-> For
Tags
I-> textbox
- > DIV
Itextarea
-> radiabutton - SPAN
- checkbox ->M1
->elasses
through N6
-> Tag Names
select 1-IDS
-button
How a JavaScript handled browse
Browser Objects handles the Document object
when any JvaScript enabled browser loadsa web page, the brower automatically creates a number of
JavaScript odjects that map to the DOM (or JSS DOAM. IN is the DOM, whkh provides Jsvascipt access Any document (ie. the HTML poge) can contain varios HTML objects wuch as:
to the HTML ojats that Images
aT contained n the web ***************** ******************************** a Image Maps
The Mavigator objecE The Web Paq
A
JATASscrip
Browser The windo object oded in the
a Hyperiinks
The JavaScript code ased windev objece J browser Frams
snippets imbedded s MAppingto the The Docunent objeet nao
containlng all Anchors
of he web mge the KTMu
5 Locatioa dbject lenents to Applets
el (e
e serea which h e Mulimedia objects such a audio files, streaning video files
hin theSCRIPT oojeetThe Riatorr
objectJavascript code O A Fom with various form elements
<SCRPT> a of T MaT Oject Tae veat objectrequires accesa. The browser creates one aAY in memory oEr HITML odisst in
filenae htmi) makes ue
the Coon Context Area**************************************
in coeputer nenory (RAN) HTML objects. the documen thus registering each of these
teract t h the HTML If these HTML
obyecs in the wed p a objects are actually contained in the HTML
slements, which will point to the contel area in page then these aTays will boid indsxsd
in in. where the HTML object are Otherwise the a y
will exist, but will be empty (i.e. have no elementsmemory

JavaScript Form Array onChange() Event


Tae JavaScript form clements amy [created by
elemenksAccess to al the fom elemects in theNetscape
form. Communicalor; occurs when the value of an element has been changed.
Taccessa
o let beld ofa fom.
tareaTo ccessa text area ol alorm. E.g. radiobuttons and checkboxes, the onchange event
ngio To accessa set of radio buttons oa the form or to access an individual radio buton within occurs when the checked state has been
set the changed.
checkborTo Bcess a checcbox oa aform. For textbox it occurs when its' content
change
Toacoess aform batloo that is Dol areset or submit button.
subat To access a 5ubmt baTton on a form.
ToBccCss aresci button on a form
Select To access a select list ofa form.
option Tbe option object is used to access the elements of a select list.
passwordo access password bcld on aform.
dden Toccessa hiddea object oa a lormn
leupload To access afile upload element of a form.

onChange() Event JavaScript Event Handler


<html> <body>
Modify the text in the input
fire the onchange event.
field, then click outside the field to JavaScript Event Handler Will Be Called When
Enter some text:
onAbort The loadiog of an image is aborted as aresuit of user
onBlur A document, window, frame set, or form element loesesaction
<input type="text" name="t«t" value="Hello"
onChange A text field, text area, file-uploaded field or sekection current input focus
is modified and loses
onchange="myFunction(this.value)" > |the current input focus.
<script> onClick A ink, client-side image map area or docurnent is
function myfunction(val) onDblClick Alink, client-side image map area or documeni is clicked
double chcke
alert("The input value has
onDrag Drop A dragged object is droPped in a window or fra
changed. The new value is: "
+
val); onError |An error occurs duriag koading of an image, window or frame
onfocus A document, window, írame set, or form element receives the curnend
</script |focus Apet
</body </html>
11/23/2021

onMouseOver() Event Validating against a regular expression


<html> <body>
<img onMouseOver="blglmg(this)"
onMouseOut="normalimg(this)" border="0" A regular expression (regex) is a
pattern that can be used to match
src="smiley.gif" alt="Smiley" width="32" height="32">
character combinations in text
<p> Function bigimgl) is triggered when the user mouse over strings, so regexs are ideal for form
the image. This function enlarges the image. validation and serve a variety of other uses in
Javaacript.
The function normallmg() is triggered when the mouse pointer a Matches one character that is a (not b, not
aa, and
is moved out of the image. That function sets the height and abc Matches a, followed by b, followed byc. so on).
width of the image back to normal.</p> ab?c-Matches a, optionally followed by a single b, followed by
(ac or abc) c.
<script>
function biglmg(x){ x.style.height "64px"; abc-Matches a, optionally followed
followed by by any number of bs,
x.style.width = "64px"; c. ( ac, abc, abbbbbc, and so on).
function normalimg(x){ x.style.height ="32px"; alb- Matches one character that is a or b.
x.style.width = "32px"; abc]xyz -Matches exactly abc or exactly
not abcXyz or a or y, and so on xyz (but
s/script> </body> s/html>

ot 2.
a tuat slícle f

Validating against a regular expression Validating


sform> built-in form validation
label for="choose">Would you prefer a banana or a cherry? Pattern
</label> minlength="6"
input id-"choose" pattern="[ebjanana | [cc]herry"> maxlength="6"
<button>Submit</button>
</form Q. JavaScript Retype Password Validation
In this example, the sinput> element accepts one of four possible

values: the strings "banana", "Banana", "cherry", or "Cherry".

Regular expressions are case-sensitive, but we've made it


support capitalized as well as lower-case versions using an extra
"Aa" pattern nested inside square brackets.

Cookies How Cookies Works?

A cookie is an amount ofinformation that persists between a When a user sends to the server, then each
a request of that
server-side and a client-side. request is treated asa new request sent by the different user.

A web browser stores this information at the time of S o , to recognize the old user, we need to add the cookie with
browsing. the response from the server.

A cookie contains the information as a string generally in the browser at the client-side.
form of a name-value palir separated by semi-colons. Now, whenever a user sends a request to the serve, the
I t maintains the state of a user and remembers the user's cookle is added with that request automatically. Due to the
information among all the web pages. cookle, the server recognizes the users.
How Cookies Works? How to create a Cookie in JavaScript?
In JavaScript, we can create, read,
update and delete a cookie
by using document.cookie
property.
eguest The following syntax is used to create
Kepone*Coolie
a
cookie
RequesteCookie
document.cookie="name=value";
Web Browiw
Server

set and get a cookie. set and get a cookie


<html> <body>
we provide choices of color and pass the selected color value to
<input type="button" value="setCookie" onclick="setCookie()">
the cookie.
sinput type="button" value="getCookie" onclick="getCookie()">
<script> Now, cookie stores the last choice of a user in a browser.
function setCookie() So, on reloading the web page, the user's last choice will be
document.cookie = "username=Duke Martin";
shown on the screen.
<html> <body>
functiongetCookie() <select id="color" onchange="display()">
iffdocument.cookie.lengthl=0) {
coption value="Select Color">Select Color</option>
alert(document.cookie);
<option value="yellow">Yellow</option>
else alert("Cookie not available"); <option value="green">Green</option>
</seript </body> </html> <option value="red">Red</option»
s/select>

set and get a cookie


Lab
<script>
function display() Set & Get Cookie
var value =document.getElementByid("color").value;
if(value I= "Select Color")
document. bgColor = value;

document.cookie "color="+value;

window.onload = function ()

if (document.cookie.length I= 0) {
var array = document.cookie.split("=");

document.getEle mentByld("color").value= array[1];


alert(arraylO]); alert{array[1]):
document.bgColor = array[1];

s/script> s/body> </html>


11/23/2021
ONU

JavaScript Timing Events setTimeout() Method

.The window object allows execution of code at specified T h e window.setTimeout() method can be written without

time intervals, are called


timing events. the window prefix.

The two key methods to use with JavaScript are: The first parameter is a function to be executed.

setTimeout (unction, The second parameter indicates the number of milliseconds


-

milliseconds)
Executes a function, after waiting a specified number of before execution.
<button onclick="setTimeout(myFunction, 3000)">Try it
milliseconds.
</button>
setintervallfunction, milliseconds) Click a button.
Wait3
Same as set Timeout(), but repeats the execution of the <script> seconds, and the page wil
function myFunction() { alert "Hello":
function continuously. alert('Hello');
</script>
Both methodsare of the HTML DOM Windowobject._

To Stop the Execution clearTimeout() Method


<button onclick="myVar = setTimeout(myFunction, 3000)"> Try
dearTimeout() method stops the execution of the function
it </button>
specified in setTimeout(0.
<button onclick="clearTimeout(myVar)">Stop it</button>
window.clearTimeout(dimeoutVariable)
C a n be written without the window prefix.
<script>
dearTimeout() method uses the variable returned function myFunction() {
alert("Hello ");
from setTimeout(): Ty it Stop t
</script Click "Try ". Walt 3 seconds.
The page will alert "Hello. the
myWar=setTimeouttfunction, milliseconds); Clck "stop" to prevent
first function to execute.
Y o u must cllck "Stop" before
clearTimeout{myVar); the 3 seconds are up.)

A script oa this page starts this clock:


setinterval() Method Display the curent time:
11 58.28 AM
<html

Repeats a given function at every given time-interval <body


<h3>A script on this page starts this clock:</h3>
window.setinterval (function, miliseconds);
<h4 id="demo"></h4

Method can be written without the window prefix.


First parameter is a function to be executed. <script>
var myVar = setinterval(myTimer, 1000);
Second parameter indicates the length of the time-interval
function myTimer() {
var d = new Date();
between each execution.
document.getElementByld("demo").innerHTML
d.tolocaleTimeString():

/script </body> </html>


clock
stars
this
this page
A script on

Stop the Execution the current


time:
53 21 PM

Display Stoptime

Stops the executions


clearlnterval() shtml>
<body> clock:</h3>
of this
the function starts

setinterval() method. specified in the sh3>A script on this page

b u t tid-"demo"></h4>
ch4 on onclick="clearinterval(myVar)">Stop time</button>

Method
window.clearinterval(timerVoriable)
can
be written <script>
without the window prefix. setinterval(myTimer,
100o);
Uses the variable myVar
varfunction myTimer() {
returned from setinterval():
var d = new Date(0
myVar =

setintervalunction, miliseconds) d o c u m e n t . g e t E l e m e n t B y l d ( " d e m o " ) . i n n e r H

d.toLocale TimeString():
T M L

clearlntenvamyvar)
</script </body </html>

Lifetime of a cookie - Lifetime of a cookie


expires attribute max-age attribute

This attribute takes an exact date (in GMT/UTC format) when optional max-age attribute
the cookie should expire, rather than an offset in seconds.
1 1 Set for 30 days

document.cookie = "firstName=Christopher

document.cookie = "firstName=Christopher max-age="+ 30*24*60 60;


expires=Thu, 31 Dec 2099 23:59:59 GMT"; Expires t maintains the state of a cookie up to the specified
date and time.

max-age - It maintains the state of a cookie up to the specified

time. Here, time is given in seconds.

Lab Lab
Q Using setTimeout() and clearTimeout() do the following
Q3.
Write JavaScript to show the usage of setinterval function using
Use button to show alert "Hello" after 3s.
which background color of a division keeps on changing to a
Use "Stop" button to prevent the first function to execute. random color every 2 seconds.
Also use setTimeout function to show the content of a textbox
Q Using setimterval() and clearintervai() as label of large size after 3 seconds.
display the current time, and stop the timer. 04.
Prompt user to enter his name and add it to cookies. If the user
is new user then show an alert box stating Welcome <user
name> otherwise display Welcome again <user name>.
Cookies should get removed already after 24 hours

You might also like