Web Design and Programming_Chapter 4
Web Design and Programming_Chapter 4
073
Chapter 4
4. Client-Side Scripting Using JavaScript
4.1. Introduction to JavaScript
JavaScript is an object-based scripting language which is lightweight and cross-platform. JavaScript is not a
compiled language, but it is a translated language. The JavaScript Translator (embedded in the browser) is
responsible for translating the JavaScript code for the web browser.
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
Displaying clocks etc.
Example: <script> document.write("Hello World"); </script>
We can create external JavaScript file and embed it in many html page. It provides code re usability because
single JavaScript file can be used in several html pages. An external JavaScript file must be saved by .js
extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the
webpage.
Let’s create an external JavaScript file that prints Hello World in a alert dialog box.
message.js
function msg(){ alert("Hello World"); }
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.
index.html
<html> <head>
<script type="text/javascript" src="message.js"></script>
</head> <body> <p>Welcome to JavaScript</p>
<form><input type="button" value="click" onclick="msg()"/>
</form> </body> </html>
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
JavaScript Output
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method. The id
attribute defines the HTML element. The innerHTML property defines the HTML content:
Example
<!DOCTYPE html><html><body>
<h1>My First Web Page</h1><p>My First Paragraph</p>
<p id="demo"></p><script>
document.getElementById("demo").innerHTML = 5 + 6;
</script></body></html>
Changing the innerHTML property of an HTML element is a common way to display data in HTML.
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html><html><body>
<h1>My First Web Page</h1><p>My first paragraph.</p><script>
document.write(5 + 6); </script></body></html>
Using document.write() after an HTML document is loaded, will delete all existing HTML. The
document.write() method should only be used for testing.
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html><html><body><h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>window.alert(5+6);</script></body></html>
Using console.log()
For debugging purposes, you can use the console.log() method to display data.
Example
<!DOCTYPE html><html><body>
<script>console.log(5 + 6);</script>
</body></html>
<script>
function copyvalue(){
var fname=form1.elements["fname"].value; // read data
document.getElementById("fnamecopy").value=fname; // write data
var sname=form1.elements["sname"].value; //read data
document.getElementById("snamecopy").value=sname; //write data
}
</script></head><body>
<form name="form1" method=”post” action=””>
First Name:<input type="text" name="fname" id="fname" /><br><br>
First Name Copy:<input type="text" name="fnamecopy" id="fnamecopy" /><br><br>
result=num1%num2;
else
alert("Invalid Operator");
document.getElementById("result").value=result;//set at result textfield
}
</script>
</head>
<body>
<form name="frm" >
First Number:<input type="text" name="num1" id="num1" /><br><br>
Second Number:<input type="text" name="num2" id="num2" /><br><br>
Operator<input type="text" name="operator" id="operator" /><br><br>
Result:<input type="text" name="result" id="result" /><br><br>
<input type="button" Value="Result" onclick="calculator()">
</form></body></html>
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Single line comments start with //. Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
Multi-line Comments
Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by
JavaScript.
Example
/* The code below will change the heading with id = "myH"
and the paragraph with id = "myP" in my web page: */
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands
JavaScript has the following operators:
Arithmetic Operators
Comparison (Relational) Operators
Bitwise Operators
Logical Operators
Assignment Operators
Special Operators
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if
statement that we have learned in previous page. But it is convenient than if..else..if because it can be used
with numbers, characters etc.
The syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
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.
There are four types of loops in JavaScript: for loop, while loop, do-while loop and for-in loop
For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of
iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
while loop
The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number
of iteration is not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code
is executed at least once whether condition is true or false. The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
for in loop
The JavaScript for in loop is used to iterate the properties of an object. The JavaScript for/in statement
loops through the properties of an object:
Example
var person = {fname:"Abel", lname:"Degu", age:25};
var text = "";
var x;
for (x in person) { text += person[x]; }
Example
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
</script>
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse
the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
Code reusability: We can call a function several times so it save coding.
Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.
Example
In this example, we are going to validate the name and password. The name can’t be empty and password
can’t be less than 6 characters long. Here, we are validating the form on form submit. The user will not be
forwarded to the next page until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
Example
<html> <head> <script type = "text/javascript">
function sayHello() { alert("Hello World"); }
</script></head> <body>
<p>Click the following button and see result</p>
<form><input type="button" onclick="sayHello()" value="Say Hello"/> </form></body>
</html>
<body>
<form method = "POST" action = "test.html" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well. The
onmouseover event triggers when you bring your mouse over any element and the onmouseout
triggers when you move your mouse out from that element. Try the following example.
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given as:
<script> var str="This is string"; document.write(str); </script>
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
4.8. Cookies
Cookies let you store user information in web pages. Cookies are data, stored in small text files, on your
computer. When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user. Cookies were invented to solve the problem "how to remember information
about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
Cookies are saved in name-value pairs like: username = John Doe
When a browser requests a web page from a server, cookies belonging to the page is added to the request.
This way the server gets the necessary data to "remember" information about users.
None of the examples below will work if your browser has local cookies support turned off.
Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {