Javascript Examples

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

JAVASCRIPT EXAMPLES

DISPLAY DATE AND TIME


<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body>
</html>

EXAMPLE USING IF..ELSE STATEMENT


<html>
<body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("<b>Good morning</b>");
}
else
{
document.write("<b>Good day</b>");
}
</script>
<p>
This example demonstrates the If...Else
statement.
</p>
<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.
</p>

ALERT BOX
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("Hello! I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()"
value="Show alert box" />
</body>
</html>

CONFIRM BOX
<html>

</body>
</html>
ALERT BOX WITH LINE BREAK
<html>
<head>
<script type="text/javascript">
function disp_alert()
{
alert("Hello again! This is how we" + '\n' + "add
line breaks to an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="disp_alert()"
value="Display alert box" />
</body>
</html>

PROMPT BOX
<html>

<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button!");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()"
value="Show a confirm box" />
</body>
</html>

<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your
name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are
you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()"
value="Show prompt box" />
</body>
</html>

You might also like