Lec 8 JS
Lec 8 JS
Functions can be called by name. The syntax for calling a function is given below
Function-name (required parameters)
In JavaScript, usually we write functions and call these functions when some event occurs. The
most common events are
onClick: when user clicks on some element
onDblClick: when user double clicks some element
onChange: when the focus is changes
onFocus: when the focus is set
onMouseOver: when the mouse is moved over an element
onMouseOut: when the mouse is moved away from an element
onSubmit: when a form is submitted
onload: when the web page is loaded in the browser window
In the following example, we have declared a function. This function asks the user to enter its
name and then writes the user’s name on the browser screen. The function is called on the
onload function of the page.
<html>
<head>
<title>Untitled Document</title>
<script language="javascript">
function getName()
{
var name=prompt("Pleae enter your name",'name')
document.write("Welcome Mr. ",name)
}
</script>
</head>
<body onload="getName()">
</body>
</html>
Prompt box: A prompt box is often used if you want the user to input a value before entering a
page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value. If the user clicks "OK" the box returns the input value. If
the user clicks "Cancel" the box returns null.
Confirm box:A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If
the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
In the following code a function conName() is written. This function asks the user to enter its
name, then a confirm box is shown to get a confirmation whether the user wants to write its
name on the browser or not. If user confirms, a welcome message for the user is written on the
browser
<html>
<head>
<title>Confirm Box</title>
<script language="javascript">
function conName()
{
var name=prompt("Your Name please!")
if(confirm("Write on the webpage ?"))
document.write("Welcome Mr." + name)
else
document.write("Welcome MR. Anonymous")
}
conName()
</script>
</head>
<body>
</body>
If user enters its name and press ok, the confirm box is displayed
Now, when user clicks the ok button, the user’s name is written on the browser