Chapter 4 JavaScript
Chapter 4 JavaScript
document.write("<h1>Hello World!</h1>");
</script>
Example Explained
To insert a JavaScript into an HTML page, we use the <script> tag.
JavaScript Statements
➢JavaScript is a sequence of statements to be executed by the browser.
➢JavaScript is Case Sensitive
Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you
write JavaScript statements, create or call variables, objects and functions.
➢JavaScript Statements
➢A JavaScript statement is a command to a browser. The purpose of the command is to tell the
browser what to do.
➢This JavaScript statement tells the browser to write "Hello
Dolly" to the web page: document.write("Hello Dolly");
➢JavaScript Code
➢JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is
executed by the browser
in the sequence they are written.
➢JavaScript Blocks
➢JavaScript statements can be grouped together in blocks.
➢Blocks start with a left curly bracket {, and ends with a right curly bracket}.
➢The purpose of a block is to make the sequence of statements execute together.
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>
➢JavaScript Comments
➢JavaScript comments can be used to make the code more readable.
➢JavaScript Single-line and Multi-Line Comments
➢Multi line comments start with /* and end with */.
➢Single line comments uses // .
➢<script type="text/javascript">
/*The code below will write one heading and two paragraphs*/
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>"); </script>
JavaScript Variables
➢Variables are "containers" for storing information.
➢JavaScript variables are used to hold values or expressions.
Rules for JavaScript variable names:
Variable names are case sensitive, for example y and Y are two different variables.
Variable names must begin with a letter or the underscore character
You should not use any of the JavaScript reserved keyword as variable name.
Declaring (Creating) JavaScript Variables
You can declare JavaScript variables with the var statement:
Example:
➢var x; var pi = 3.1416;
➢var carname=”volvo”; Var str= “Hello world";
➢After the declaration shown above, the variable x is empty (no values yet). However, you can
also assign values to the variable when you declare it.
➢Given that x=6 and y=3, the table below explains the logical operators
Logical Operators
Logical operators are used to determine the logic between variables or values.
There is an operator called conditional operator. This first evaluates an expression for a true or false value
and then execute one of the two given statements depending upon the result of the evaluation. The
conditional operator has this syntax:
Operato Descriptio
Example
r n
Conditional statements
➢Conditional statements are used to perform different actions based on different conditions.
➢Very often when you write code, you want to perform different actions for different decisions.
➢You can use conditional statements in your code to do this.
➢In JavaScript we have the following conditional statements:
If Statement
➢if statement - use this statement to execute some code only if a specified condition is true.
Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
➢<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date(); var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
If...else Statement
➢if...else statement - use this statement to execute some code if the condition is true and another code if the
condition is –
false. Syntax:
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
➢<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
Example:
<html><body>
<script type="text/javascript">
for(i=0;i<10;i++){
document.write("The number is: " + i);
document.write("<br />");
}</script>
</body></html>
JavaScript Loops/while Loop/
while - loops through a block of code while a specified condition is true Syntax:
while (var<=endvalue) while (expression){
{ Statement(s) to be executed if expression is true
code to be executed }
}
Example: <html><body>
<script type="text/javascript"> i=0; while (i<=5)
{
document.write("The number is " + i); document.write("<br />"); i++;
}
</script></body>/html>
The do...while Loop
➢This loop will execute the block of code once, and then it will repeat the loop as long as the specified condition
is true.
Syntax: do{
Statement(s) to be executed;
} while (expression);
Note the semicolon used at the end of the do...while loop.
Example: <script type="text/javascript">
var x = 1;
var sum = 0;
while ( x <= 10 ) { // loop until x is > 10
sum += x; // add x to the running sum
x++;}
document.write("The total sum is: " + sum); </script>
The break and continue statements
➢The break statement will terminate execution of the loop and continue executing the code that follows after
the loop (if any).
}</script>
JavaScript Functions
A function is a group of reusable code which can be called anywhere in your programme. This eliminates the
need of writing same code again and again. This will help programmers to write modular code. You can divide
your big programme in a number of small and manageable functions. Like any other advance programming
language, JavaScript also supports all the features necessary to write modular code using functions.
A function will be executed by an event or by a call to the function.
To keep the browser from executing a script when the page loads, you can put your script into a function.
You may call a function from anywhere within a page (or even from other pages if the function is
embedded in an
JavaScript lets you define functions using the function keyword
Functions can return values using the return keyword.
Syntax:
function function name(var1,var2,...,varX)
{ some code
}
➢The parameters var1, var2, etc. are variables or values passed into the function.
➢The { and the } defines the start and end of the function.
Example:
A simple function that takes no parameters called sayHello is defined here:
<script type="text/javascript"><!--
function sayHello()
{alert("Hello there");
}
//-->
JavaScript Events
What is Event?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
By using JavaScript, we have the ability to create dynamic web pages.
Events are actions that can be detected by JavaScript.
Events are signals generated by the browser when various actions occur.
Every element on a web page has certain events which can trigger a JavaScript.
We define the events in the HTML tags.
Events are normally used in combination with functions, and the function will not be executed before the
event occurs!
JavaScript enables the designer of an HTML page to take advantage of events for automated navigation,
client-side processing, and more.
Example:-
When the page loads, it is called an event.
When the user clicks a button, that click too is an event.
When an image has been loaded
When the mouse clicks and moves over an element
When an input field is changed
Document Object
Example:
<html><body>
<script type="text/javascript">
document.write("Hello World!") // Write text to the output
document.write("<h1>Hello World!</h1>") // Write text with Formatting to the output
</script> </body></html>
Document Object: Use getElementsByName()
Example:
<html>
<head>
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("myInput")
alert(x.length + " elements!")
}</script></head><body>
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<br />
<input type="button" onclick="getElements()" value="How many elements named
'myInput'?">
</body></html>
Document Object: Return the innerHTML of the first anchor in a document
Example:
<html><body>
<a name="first">First anchor</a><br />
<a name="second">Second anchor</a><br />
<a name="third">Third anchor</a><br /><br />
InnerHTML of the first anchor in this document:
<script type="text/javascript">
document.write(document.anchors[0].innerHTML)
</script>
</body>
</html>
References
HTML Tutorial: http://www.w3schools.com/html
CSS Tutorial: http://www.w3schools.com/css
JavaScript Tutorial: http://www.w3schools.com/js