Unit 5 JavaScript
Unit 5 JavaScript
Javascript is the most popular programming language in the world and that makes it a
programmer‟s great choice. Once you learnt Javascript, it helps you developing great
front-end as well as back-end softwares using different Javascript based frameworks like
jQuery, Node.JS etc.
Javascript is everywhere, it comes installed on every modern web browser and so to learn
Javascript you really do not need any special environment setup. For example Chrome,
Mozilla Firefox , Safari and every browser you know as of today, supports Javascript.
Javascript helps you create really beautiful and crazy fast websites. You can develop your
website with a console like look and feel and give your users the best Graphical User
Experience.
JavaScript usage has now extended to mobile app development, desktop app
development, and game development. This opens many opportunities for you as
Javascript Programmer.
Due to high demand, there is tons of job growth and high pay for those who know
JavaScript. You can navigate over to different job sites to see what having JavaScript
skills looks like in the job market.
Great thing about Javascript is that you will find tons of frameworks and Libraries
already developed which can be used directly in your software development to reduce
your time to market.
There could be 1000s of good reasons to learn Javascript Programming. But one thing for sure,
to learn any programming language, not only Javascript, you just need to code, and code and
finally code until you become expert.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features −
Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
JavaScript cannot be used for networking applications because there is no such support
available.
JavaScript doesn't have any multi-threading or multiprocessor capabilities.
JavaScript - Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
Hello World!
JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the data
type. It can hold any type of values such as numbers, strings etc. For example:
1. var a=40;//holding number
2. var b="Rahul";//holding string
Variables in JavaScript: Variables in JavaScript are containers that hold reusable data. It is the
basic unit of storage in a program.
Before ES2015, JavaScript variables were solely declared using the var keyword followed by
the name of the variable and semi-colon. Below is the syntax to create variables in JavaScript:
var var_name;
var x;
The var_name is the name of the variable which should be defined by the user and should be
unique. These types of names are also known as identifiers. The rules for creating an identifier
in JavaScript are, the name of the identifier should not be any pre-defined word(known as
keywords), the first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent
characters may be any letter or digit or an underscore or dollar sign.
Notice in the above code sample, we didn‟t assign any values to the variables. We are only
saying they exist. If you were to look at the value of each variable in the above code sample, it
would be undefined.
We can initialize the variables either at the time of declaration or also later when we want to use
them.
// Initializing variables
var name = "Harsh";
name = "Rakesh";
JavaScript is also known as untyped language. This means, that once a variable is created in
JavaScript using the keyword var, we can store any type of value in this variable supported by
JavaScript.
The above example executes well without any error in JavaScript, unlike other programming
languages.
Variables in JavaScript can also evaluate simple mathematical expressions and assume their
value.
Variable Scope in Javascript: The scope of a variable is the part of the program from which the
variable may directly be accessible.
Let‟s look at the code below. We have a global variable defined in the first line in the global
scope. Then we have a local variable defined inside the function fun().
Example:
function fun() {
let localVar = "This is a local variable";
console.log(globalVar);
console.log(localVar);
}
fun();
Output:
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
Output:
1
2
3
4
5
1. while (condition)
2. {
3. code to be executed
4. }
1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </script>
Output:
11
12
13
14
15
1. do{
2. code to be executed
3. }while (condition);
1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>
8. Output:
9. 21
22
23
24
25
Syntax:
Important Points:
Use the for-in loop to iterate over non-array objects. Even though we can use a for-in
loop for an array, it is generally not recommended. Instead, use a for loop for looping
over an array.
The properties iterated with the for-in loop also include the properties of the objects
higher in the Prototype chain.
The order in which properties are iterated may not match the properties that are defined
in the object.
If statement
Syntax:
if(condition)
{
lines of code to be executed if condition is true
}
You can use if statement if you want to check only a specific condition.
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
if(age>=18)
</script>
</head>
<body>
</body>
</html>
If…Else statement
Syntax:
if(condition)
{
lines of code to be executed if the condition is true
}
else
{
lines of code to be executed if the condition is false
}
You can use If….Else statement if you have to check two conditions and execute a different set of
codes.
<html>
<head>
<title>If...Else Statments!!!</title>
<script type="text/javascript">
// Get the current hours
var hours = new Date().getHours();
if(hours<12)
document.write("Good Morning!!!<br />");
else
document.write("Good Afternoon!!!<br />");
</script>
</head>
<body>
</body>
</html>
You can use If….Else If….Else statement if you want to check more than two conditions.
<html>
<head>
<script type="text/javascript">
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one + " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");
</script>
</head>
<body>
</body>
</html>
Functions in JavaScript
A function is a set of statements that take inputs, do some specific computation, and produce
output. The idea is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we can call that
function.
Example 1: A basic javascript function, here we create a function that divides the 1st element by
the second element.
return g1 / g2;
console.log(value);
Output:
To create a function in JavaScript, we have to first use the keyword function, separated by the
name of the function and parameters within parenthesis. The part of the function inside the curly
braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for assignments, or calculations.
Function Definition: Before, using a user-defined function in JavaScript we have to create one.
We can use the above syntax to create a function in JavaScript. A function definition is
sometimes also termed a function declaration or function statement. Below are the rules for
creating a function in JavaScript:
Every function should begin with the keyword function followed by,
A user-defined function name that should be unique,
A list of parameters enclosed within parentheses and separated by commas,
A list of statements composing the body of the function enclosed within curly braces {}.
console.log(calcAddition(6,9));
Output
15
This function accepts two numbers as parameters and returns the addition of these two
numbers.
Accessing the function with just the function name without () will return the function
object instead of the function result.
Syntax:
Function Expression: It is similar to a function declaration without the function name. Function
expressions can be stored in a variable assignment.
Syntax:
};
console.log(x);
Output
16
Arrow Function: It is one of the most used and efficient methods to create a function in
JavaScript because of its comparatively easy implementation. It is a simplified as well as a more
compact version of a regular or normal function expression or syntax.
Syntax:
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Function Parameters: Till now, we have heard a lot about function parameters but haven‟t
discussed them in detail. Parameters are additional information passed to a function. For
example, in the above example, the task of the function calcAddition is to calculate the addition
of two numbers. These two numbers on which we want to perform the addition operation are
passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in JavaScript can have
any number of parameters and also at the same time, a function in JavaScript can not have a
single parameter.
function multiply(a, b) {
return a * b;
console.log(multiply(69)); // 69
Output
69
Calling Functions: After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the value of parameters
enclosed between the parenthesis and a semicolon at the end. The below syntax shows how to
call functions in JavaScript:
Syntax:
Example 5: Below is a sample program that illustrates the working of functions in JavaScript:
function welcomeMsg(name) {
}
// creating a variable
console.log(welcomeMsg(nameVal));
Output:
Return Statement: There are some situations when we want to return some values from a
function after performing some operations. In such cases, we can make use of the return
statement in JavaScript. This is an optional statement and most of the time the last statement in a
JavaScript function. Look at our first example with the function named as calcAddition. This
function is calculating two numbers and then returns the result.
Syntax: The most basic syntax for using the return statement is:
return value;
JavaScript Arrays
JavaScript Array is a single variable that is used to store elements of different data types.
JavaScript arrays are zero-indexed. The Javascript Arrays are not associative in nature.
Arrays are used when we have a list of items. An array allows you to store several values with
the same name and access them by using their index number.
Declaration of an Array
console.log(courses)
Output
arr1[0] = 10
arr1[1] = 20
arr1[2] = 30
Output
Note: Both the above methods do exactly the same. Use the array literal method for efficiency,
readability, and speed.
Accessing Elements of an Array
Any element in the array can be accessed using the index number. The index in the arrays starts
with 0.
console.log(courses[0])
console.log(courses[1])
console.log(courses[2])
Output
HTML
CSS
Javascript
We will use index based method method to change the elements of array.
console.log(courses)
courses[1]= "GeeksforGeeks"
console.log(courses)
Output
console.log(courses.toString())
Output
HTML,CSS,Javascript
Increase and decrease the length of an array
We can increase and decrease the length of an array using the Javascript‟s length property.
Output
Array after increased length: [ 'HTML', 'CSS', 'Javascript', <2 empty items>
]
Array after decreased length: [ 'HTML', 'CSS' ]
courses[3] = 'PhP'
courses[4] = 'React'
Output
Array after increased length: [ 'HTML', 'CSS', 'Javascript', <2 empty items>
]
Array after initializing: [ 'HTML', 'CSS', 'Javascript', 'PhP', 'React' ]
We can loop through the elements of a Javascript array using the for loop:
console.log(courses[i])
}
Output
HTML
CSS
Javascript
courses.forEach(myfunc);
function myfunc(elements) {
console.log(elements);
Output
HTML
CSS
Javascript
Using the Javascript in-built push() method we can add new elements to an array.
courses.push("React")
Output
We can also add a new element to a Javascript array using the length property.
Output
console.log(typeof courses)
Output
object
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser. When javascript
code is included in HTML, js react over these events and allow the execution. This process of
reacting over the events is called Event Handling. Thus, js handles the HTML events via Event
Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
Mouse events:
Event Performed Event Handler Description
Click Onclick When mouse click on an element
Mouseover onmouseover When the cursor of the mouse comes over the element
Mouseout Onmouseout When the cursor of the mouse leaves an element
Mousedown onmousedown When the mouse button is pressed over the element
Mouseup Onmouseup When the mouse button is released over the element
Mousemove onmousemove When the mouse movement takes place.
Keyboard events:
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Event Performed Event Handler Description
Focus onfocus When the user focuses on an element
Submit onsubmit When the user submits the form
Blur onblur When the focus is away from a form element
Change onchange When the user modifies or changes the value of a form element
Window/Document events
Event Event Description
Performed Handler
Load onload When the browser finishes the loading of the page
Unload onunload When the visitor leaves the current webpage, the browser unloads
it
Resize onresize When the visitor resizes the window of the browser
Let's discuss some examples over events and their handlers.
Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>
MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>
Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>
Keydown Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. document.getElementById("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>
Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6. <!--
7. document.write("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>
JavaScript String
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal
is given below:
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
Output:
1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>
Output:
Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified
index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
match() It searches a specified regular expression in a given string and returns
that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified
starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified
index.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s
current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s
current locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created
array.
trim() It trims the white space from the left and right side of the string.
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Output:
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Output:
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Output:
11
Output:
16
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Output:
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>
Output:
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Output:
cde
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Output:
javascript trim
1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
The Math functions consist of methods and properties. Following is the list of methods used with
the Math object:
1. Math.round()
This method provides the value of the given number to a rounded integer. It can be written as:
Math.round(x), where x is a number.
2. Math.pow()
3. Math.sqrt()
4. Math.abs()
It provides the absolute i.e. positive value of a number. It can be written as:
Math.abs(x); where x is a number.
5. Math.ceil()
It gives a smaller number, which is greater or equal to the given integer. It can be written as:
Math.ceil(x); where x is a number
6. Math.floor()
It gives a larger number, which is lesser or equal to the given integer. It can be written as:
Math.floor(x); where x is a number.
7. Math.sin()
8. Math.cos()
The min() method is used to display the lowest value of the given arguments. It can be written
as:
Math.min(val1, val2………valn); where val1, val2………valn are numbers.
The max() method is used to display the highest value of the given arguments. It can be written
as:
Math.max(val1, val2………valn); where val1, val2………valn are numbers.
10. Math.random()
11. Math.acos()
12. Math.asin()
Examples
Let us see few examples for the above some methods of JavaScript Math Functions:
Math.abs()
Code:
<!DOCTYPE html>
<html>
<body>
<p id="abs_demo"></p>
<script>
document.getElementById("abs_demo").innerHTML = Math.abs(-5.6);
</script>
</body>
</html>
Output:
5.6
JavaScript Form
In this tutorial, we will learn, discuss, and understand the JavaScript form. We will also see the
implementation of the JavaScript form for different purposes.
Here, we will learn the method to access the form, getting elements as the JavaScript form's
value, and submitting the form.
Introduction to Forms
Forms are the basics of HTML. We use HTML form element in order to create the JavaScript
form. For creating a form, we can use the following sample code:
1. <html>
2. <head>
3. <title> Login Form</title>
4. </head>
5. <body>
6. <h3> LOGIN </h3>
7. <formform ="Login_form" onsubmit="submit_form()">
8. <h4> USERNAME</h4>
9. <input type="text" placeholder="Enter your email id"/>
10. <h4> PASSWORD</h4>
11. <input type="password" placeholder="Enter your password"/></br></br>
12. <input type="submit" value="Login"/>
13. <input type="button" value="SignUp" onClick="create()"/>
14. </form>
15. </html>
In the code:
Form name tag is used to define the name of the form. The name of the form here is
"Login_form". This name will be referenced in the JavaScript form.
The action tag defines the action, and the browser will take to tackle the form when it is
submitted. Here, we have taken no action.
The method to take action can be either post or get, which is used when the form is to be
submitted to the server. Both types of methods have their own properties and rules.
The input type tag defines the type of inputs we want to create in our form. Here, we have
used input type as 'text', which means we will input values as text in the textbox.
Net, we have taken input type as 'password' and the input value will be password.
Next, we have taken input type as 'button' where on clicking, we get the value of the form
and get displayed.
Other than action and methods, there are the following useful methods also which are provided
by the HTML Form Element
Referencing forms
Now, we have created the form element using HTML, but we also need to make its connectivity
to JavaScript. For this, we use the getElementById () method that references the html form
element to the JavaScript code.
Next, we need to submit the form by submitting its value, for which we use the onSubmit()
method. Generally, to submit, we use a submit button that submits the value entered in the form.
When we submit the form, the action is taken just before the request is sent to the server. It
allows us to add an event listener that enables us to place various validations on the form.
Finally, the form gets ready with a combination of HTML and JavaScript code.
Let's collect and use all these to create a Login form and SignUp form and use both.
Login Form
1. <html>
2. <head>
3. <title> Login Form</title>
4. </head>
5. <body>
6. <h3> LOGIN </h3>
7. <formform ="Login_form" onsubmit="submit_form()">
8. <h4> USERNAME</h4>
9. <input type="text" placeholder="Enter your email id"/>
10. <h4> PASSWORD</h4>
11. <input type="password" placeholder="Enter your password"/></br></br>
12. <input type="submit" value="Login"/>
13. <input type="button" value="SignUp" onClick="create()"/>
14. </form>
15. <script type="text/javascript">
16. function submit_form(){
17. alert("Login successfully");
18. }
19. function create(){
20. window.location="signup.html";
21. }
22. </script>
23. </body>
24. </html>
The output of the above code on clicking on Login button is shown below:
SignUp Form
1. <html>
2. <head>
3. <title> SignUp Page</title>
4. </head>
5. <body align="center" >
6. <h1> CREATE YOUR ACCOUNT</h1>
7. <table cellspacing="2" align="center" cellpadding="8" border="0">
8. <tr><td> Name</td>
9. <td><input type="text" placeholder="Enter your name" id="n1"></td></tr>
10. <tr><td>Email </td>
11. <td><input type="text" placeholder="Enter your email id" id="e1"></td></tr>
12. <tr><td> Set Password</td>
13. <td><input type="password" placeholder="Set a password" id="p1"></td></tr>
14. <tr><td>Confirm Password</td>
15. <td><input type="password" placeholder="Confirm your password" id="p2"></td></tr>
16. <tr><td>
17. <input type="submit" value="Create" onClick="create_account()"/>
18. </table>
19. <script type="text/javascript">
20. function create_account(){
21. var n=document.getElementById("n1").value;
22. var e=document.getElementById("e1").value;
23. var p=document.getElementById("p1").value;
24. var cp=document.getElementById("p2").value;
25. //Code for password validation
26. var letters = /^[A-Za-z]+$/;
27. var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
28. //other validations required code
29. if(n==''||e==''||p==''||cp==''){
30. alert("Enter each details correctly");
31. }
32. else if(!letters.test(n))
33. {
34. alert('Name is incorrect must contain alphabets only');
35. }
36. else if (!email_val.test(e))
37. {
38. alert('Invalid email format please enter valid email id');
39. }
40. else if(p!=cp)
41. {
42. alert("Passwords not matching");
43. }
44. else if(document.getElementById("p1").value.length > 12)
45. {
46. alert("Password maximum length is 12");
47. }
48. else if(document.getElementById("p1").value.length < 6)
49. {
50. alert("Password minimum length is 6");
51. }
52. else{
53. alert("Your account has been created successfully... Redirecting to JavaTpoint.com");
54. window.location="https://www.javatpoint.com/";
55. }
56. }
57. </script>
58. </body>
59. </html>
Window Object
Window is the object of browser, it is not the object of javascript. The javascript objects are
string, array, date etc.
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
It displays the confirm dialog box. It has message with ok and cancel buttons.
1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>
It displays prompt dialog box for input. It has message and textfield.
1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
JavaScript - Document Object Model or DOM
Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or
DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.
Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object − Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
Form object − Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements − The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.
There are several DOMs in existence. The following sections explain each of these DOMs in
detail and describe how you can use them to access and modify document content.
The Legacy DOM − This is the model which was introduced in early versions of
JavaScript language. It is well supported by all browsers, but allows access only to
certain key portions of documents, such as forms, form elements, and images.
The W3C DOM − This document object model allows access and modification of all
document content and is standardized by the World Wide Web Consortium (W3C). This
model is supported by almost all the modern browsers.
The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's
Internet Explorer browser. IE 5 and later versions include support for most basic W3C
DOM features.
DOM compatibility
If you want to write a script with the flexibility to use either W3C DOM or IE 4 DOM depending
on their availability, then you can use a capability-testing approach that first checks for the
existence of a method or property to determine whether the browser has the capability you
desire. For example −
if (document.getElementById) {
// If the W3C method exists, use it
} else if (document.all) {
// If the all[] array exists, use it
} else {
// Otherwise use the legacy DOM
}