0% found this document useful (0 votes)
57 views50 pages

Event Handling & Mathematical Methods: (Javascript)

The document discusses event handling in JavaScript. It defines event handling as capturing events and responding to them. Events can be things a user does, like clicking a mouse, or things the system does, like updating a clock. Programs that can capture and respond to events are called event-driven programs, and JavaScript was designed for writing such programs. Event handlers can be placed in HTML tags and defined with inline JavaScript, or they can be defined in external JavaScript functions that are called by event attributes in HTML tags. Common event handlers discussed include onclick, onmouseover, onfocus, onblur, onload, and unload.

Uploaded by

Rajiiii232312
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
57 views50 pages

Event Handling & Mathematical Methods: (Javascript)

The document discusses event handling in JavaScript. It defines event handling as capturing events and responding to them. Events can be things a user does, like clicking a mouse, or things the system does, like updating a clock. Programs that can capture and respond to events are called event-driven programs, and JavaScript was designed for writing such programs. Event handlers can be placed in HTML tags and defined with inline JavaScript, or they can be defined in external JavaScript functions that are called by event attributes in HTML tags. Common event handlers discussed include onclick, onmouseover, onfocus, onblur, onload, and unload.

Uploaded by

Rajiiii232312
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 50

Event Handling & Mathematical

Methods
(JavaScript)

1
Today’s Goal:
Event Handlers
• To become able to appreciate the concept of
event handlers:
– What are they?
– What do they do?
– How do we benefit from them?

• To learn to write simple programs that use


event handlers
2
What is Event Handling?
• Capturing events and responding to them

• The system sends events to the program and


the program responds to them as they arrive

• Events can include things a user does - like


clicking the mouse - or things that the system
itself does - like updating the clock. Today we
will exclusively focus on user-events
3
Event Driven Programs
• Programs that can capture and respond to
events are called ‘event-driven programs’

• JavaScript was specifically designed for writing


such programs

• Almost all programs written in JavaScript are


event-driven

4
JavaScript Handling of Events
• Events handlers are placed in the BODY part of
a Web page as attributes in HTML tags

• Events can be captured and responded to


directly with JavaScript one-liners embedded in
HTML tags in the BODY portion

• Alternatively, events can be captured in the


HTML code, and then directed to a JavaScript
function for an appropriate response 5
Let’s now revisit lecture 11 where we
introduced event handlers for the first
time

6
7
<INPUT
type=“submit”
name=“sendEmail”
value=“Send eMail”
onMouseOver=
“if (document.sendEmail.sender.value == “”)
window.alert(‘Empty From field! Please correct’)”
>

Additional JavaScript code for the smart ‘Send


eMail’ button that does not allow itself to be
8
clicked if the “From” text field is left blank
That was event handling through
what we may call ‘in-line JavaScript’

That is, the event was captured and


handled with a JavaScript one-liner
that was embedded in the HTML tag

9
In-Line JavaScript Event Handling (1)
• Event handlers are placed in the BODY portion
of a Web page as attributes of HTML tags

• The event handler attribute consists of 3 parts:


1. The identifier of the event handler
2. The equal sign
3. A string consisting of JavaScript statements
enclosed in double or single quotes

10
In-Line JavaScript Event Handling (2)
• Multiple JavaScript statements (separated by
semicolons) can be placed in that string, but all
have to fit in a single line; no newline
characters are allowed in that string

• Due to this limitation, sophisticated event


handling is not possible with in-line event
handling

11
Another - more sophisticated - way of
accomplishing the same task

12
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

function checkForm() {
if ( document.sendEmail.sender.value == “”) {
window.alert( “Empty From field! Please correct” );
}
}

JavaScript included as an attribute of the “Send eMail” button:

onMouseOver=“checkForm( )”

13
Usage Guideline
• For very short scripts, “all code in the tag”
works well

• The “code in the HEAD portion” is the right


choice for developing larger JavaScript scripts
– It makes the code easier to read
– It allows the reuse of a function for multiple event
handlers

14
Another event-handling example; this
time from lecture 11

15
16
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

function uolWindow() {
window.open(“http://www.uol.edu.pk/”) ;
}

JavaScript included as an attribute of the “New Window” button:

onClick=“uolWindow()”
17
A Few of My Favorite Event Handlers
onClick
onDblClick
onMouseOver
onMouseDown
onFocus
onBlur
onReset
onSubmit
onLoad
onUnload
18
There are many more: there is an
expanded, but still incomplete list in
your book

Now let’s look at some of these error


handlers in a bit more detail

19
onFocus & onBlur
• onFocus executes the specified JavaScript
code when a window receives focus or when a
form element receives input focus

• onBlur executes the specified JavaScript code


when a window loses focus or a form element
loses focus

20
21
JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

function checkAge( ) {
if( parseInt( document.form1.age.value ) < 12 ) {
window.alert( "Stop! You are younger than 12" ) ;
}
}

JavaScript included as an attribute of the INPUT tag:

<INPUT type="text" name="age"


onBlur="checkAge( ) "
> 22
<HTML><HEAD>
<TITLE>onBlur( ) Demo</TITLE>
<SCRIPT>
function checkAge() {
if( parseInt(document.form1.age.value) < 12) {
window.alert("Stop! You are younger than 12" ) ;
}
}
</SCRIPT>
</HEAD>
<BODY bgcolor="#66FFCC">
<FORM name="form1" method="post" action="">
<TABLE border="1">
<TR> <TD>Age</TD>
<TD><INPUT type="text" name="age" onBlur="checkAge()">
</TD></TR><TR> <TD>Phone Number</TD>
<TD><INPUT type="text" name="phNo"></TD>
</TR><TR> <TD><INPUT type="reset" value="Reset"></TD>
<TD><INPUT type="submit" value="Submit"></TD></TR>
</TABLE></FORM></BODY></HTML> 23
onLoad & onUnload
• onLoad executes the specified JavaScript code
when a new document is loaded into a window

• onUnload executes the specified JavaScript


code when a user exits a document

• What is the key difference between these 2 and


the 4 event handlers (onMouseOver, onClick,
onFocus, onBlur) that we have used so far?
24
• The onUnload attribute fires once a page has
unloaded (or the browser window has been
closed).

• onUnload occurs when the user navigates


away from the page (by clicking on a link,
submitting a form, closing the browser
window, etc.)

• Note: If you reload a page, you will also


trigger the unload event (and the onLoad
event). 25
26
• <!DOCTYPE html>
• <HTML>
• <TITLE>Example of onLoad Event Handler</TITLE>
• <HEAD>
• <SCRIPT type=“text/javascript">
• function hello(){
• window.alert("Hello there...\nThis is an example of onLoad.");
• }
• </SCRIPT>
• </HEAD>

• <BODY onLoad="hello()">

• <H3>Example of onLoad Event Handler</H3>

• </BODY>
• </HTML>
27
28
<HTML>
<HEAD>
<TITLE>onLoad Demo</TITLE>
<SCRIPT type=“text/JavaScript">
var seconds = 0;
// called when the page loads to begin the timer
function startTimer() {
// 1000 milliseconds = 1 second
window.setInterval("updateTime()", 1000);
}

// called every 1000 ms to update the timer


function updateTime() {
++seconds;
document.getElementById("time").innerHTML = seconds;
}
</SCRIPT>
</HEAD>
<BODY onLoad = "startTimer()">
<p>Seconds you have spent viewing this page so far:<br>
<strong id = "time">0</strong></p> 29
</BODY></HTML>
More Uses for onLoad/onUnload?
• onLoad can be used to open multiple Windows
when a particular document is opened

• onUnload can be used to say “Thank you for


the visit” when a user is leaving a Web page

• At times, a user opens multiple inter-dependent


windows of a Web site (e.g.). onUnload can be
used to warn that all child Windows will become
inoperable if the user closes the parent Window
30
Enhancing Forms with JavaScript
• We do care about several things.
– First values of individual form elements.
– Event cause by those form element.
– Event of entire form itself particular submitting
the form.

• You have given form and field inside it


their own ids then you can ofcourse use
document.getElementById(“”); to retrieve
either the form or any field in the form.
31
• Or if your HTML form have either the name
property, you can use following format too:

document.forms.frmcontact

32
Text Fields

• Main properties
myTextField.value

• Main Events
onfocus (the element trigger onfocus when go into it)
onblur (trigger when you leave it, onblur is always call
when you leave the field)
onchange, onkeypress, onkeydown, onkeyup

33
CheckBoxes and Radio Buttons

• Main properties
myCheckBox.checked (true or false)

• Main Events
onclick
onchange

34
Form Events

Main Events
onsubmit

35
A Note on Syntax (1)
• Mixed-case capitalization of event handlers
(e.g. onClick) is a convention (but not a
requirement) for JavaScript event handlers
defined in HTML code. Using ‘ONCLICK’ or
‘onclick’ as part of a an HTML tag is perfectly
legal as well

36
A Note on Syntax (2)
• At times, you may wish to use event handlers in
JavaScript code enclosed in <SCRIPT>,
</SCRIPT> tags

• In those cases you have to strictly follow the


JavaScript rule for all event handler identifiers:
they must all be typed in small case, e.g.
‘onclick’ or ‘onmouseover’

37
A misleading statement from Lecture 11
• I stated:
JavaScript is case sensitive. Only the first of the
following will result in the desired function – the rest
will generate errors or other undesirable events:
– onMouseClick – OnMouseClick
– onmouseclick – ONMOUSECLICK

• That statement is incorrect in two ways:


1. All four will work fine as part of HTML tags
2. Only the ‘all small case’ version will be interpreted
as intended in JavaScript code 38
MATH Object
• Math.PI
– A property that gave us the value of Pi

• Math.round( )
– A method that rounded a number to its nearest
integer

• Math.sin( )
– A method that gave us the sine of an angle

• All 3 belong to JavaScript’s Math object 39


Mathematical Functions in JavaScript
• In addition to the simple arithmetic operations
(e.g. +, *, etc.) JavaScript supports several
advanced mathematical operations as well

• Notationaly, these functions are accessed by


referring to various methods of the Math object

• Moreover, this object also contains several


useful mathematical constants as its properties

• This object has no use, but of a placeholder


40
Properties
Math.PI
Note the
Math.E CAPITAL
Math.LN2 lettering
Math.LN10 of all
properties
Math.LOG2E
Math.LOG10E
Math.SQRT2
Math.SQRT1_2
41
Methods
sin( r ) sqrt( x ) round( x )
cos( r ) pow( x, y ) floor( x )
tan( r ) ceil( x )
asin( x ) exp( x )
acos( x ) log( x ) abs( x )
atan( x )
atan2( x, y ) max( x, y )
min( x, y )

random( )
42
sin( r ), cos( r ), tan( r )
Standard trigonometric functions

Returns the sine, cosine or tangent of ‘r’,


where ‘r’ is specified in radians

EXAMPLE
document.write( Math.cos( Math.PI / 4 ) )

0.7071067811865476
43
asin( x ), acos( x ), atan( x )
Standard inverse-trigonometric functions

Returns the arcsine, arccosine or arctangent of ‘r’


in radians

EXAMPLE
document.write( Math.asin( 1 ) )

1.5707963267948965
44
sqrt( x ) pow( x, y )
Returns the Returns x
square root of raised to the
x power y

0.5  0.7071 2, 32 
4294967296

45
exp( x ) log( x )
Returns Returns the
Math.E raised the natural
to the power x logarithm of x

1  2.718281 Math.E  1

46
round( x ) floor( x ) ceil( x )
Returns Returns Returns
integer largest integer smallest
nearest to x that is less integer that is
than or equal greater than
to x or equal to x
1.1  1 1.1  1 1.1  2
12.5  13 12.5  12 12.5  13
-13.9  -14 -13.9  -14 -13.9  -13
47
abs( x )
Returns the
absolute value
of x

1.1  1.1
-12.5  12.5
00
48
random( )
Returns a randomly-selected, floating-point
number between 0 and 1

EXAMPLE
document.write( Math.random( ) )

0.9601111965589273

49
During Today’s Lecture …
• We looked at the concept of event-driven
programs and event handlers
– What are they?
– What do they do?
– How do we benefit from them?

• We wrote simple programs to demonstrate the


capabilities of a few event handlers
• We looked at the properties and methods of
JavaScript’s Math object
50

You might also like