You are on page 1of 38

JAVASCRIPT

Table of Content
Lesson Content Page
Lesson 1 Introduction 1
1.1 What is JavaScript ? 1
1.2 Client-side JavaScript 1
1.3 Advantages of JavaScript 2
1.4 Limitations of JavaScript 2
1.5 JavaScript Development Tools 3
1.6 Where is JavaScript Today? 3
1.6.1 JavaScript in Internet Explorer 4
1.6.2 JavaScript in Firefox 4
1.6.3 JavaScript in Chrome 4
1.6.4 JavaScript in Opera 5
1.6.5 Why study Javascript? 5
1.7 Exercise 6

Lesson 2 Javascript syntax 7


2.1 Introduction 7
2.2 Whitespace and Line Breaks 7
2.3 Semicolons are Optional 8
2.4 Case Sensitivity 8
2.5 Comments in JavaScript 8
2.6 JavaScript in <head>...</head> section 9
2.7 JavaScript in <body>...</body> section 10
2.8 JavaScript in <body> and <head> Sections 10
2.9 JavaScript in External File 11
2.10 Exercise 11

Lesson 3 Changing content 12


3.1 JavaScript Can Change HTML Content 12
3.2 JavaScript Can Change HTML Attributes 12
3.3 JavaScript Display Possibilities 16
3.4 Using window.alert() 16
3.5 Using document.write() 16
3.6 Using innerHTML 17
3.7 Using console.log() 17
3.8 Exercise 18

Lesson 4 Javascript Statements and functions 19


4.1 JavaScript Statements 19
4.2 JavaScript Programs 19
4.3 JavaScript Values 20
4.4 JavaScript Literals 20
4.5 JavaScript Variables 22
4.6 Much Like Algebra 23
4.7 JavaScript Data Types 24

Lesson 5 Javascript Operator 25


5.1 Introduction 25
5.2 Exercise 27

i
JAVASCRIPT

Lesson 6 Simple JQuery 29


6.1 What is jQuery? 29
6.2 Adding jQuery to Your Web Pages 29
6.2.1 Downloading jQuery 29
6.2.2 jQuery CDN 30
6.3 jQuery hide() and show() 32
6.4 jQuery toggle() 34
6.5 Exercise 35

ii
JAVASCRIPT

LESSON 1 INTRODUCTION
JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications. It is complimentary to and integrated with Java. JavaScript is
very easy to implement because it integrates with HTML. It is open and cross-platform.

1.1 What is JavaScript?


Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has
been embedded in Netscape, Internet Explorer, and other web browsers.

The ECMA-262 Specification defined a standard version of the core JavaScript language.

JavaScript is a lightweight, interpreted programming language.


Designed for creating network-centric applications.
Complementary to and integrated with Java.
Complementary to and integrated with HTML.
Open and cross-platform

1.2 Client-side JavaScript


Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.

1
JAVASCRIPT

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.

1.3 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.

1.4 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 multithreading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.

2
JAVASCRIPT

1.5 JavaScript Development Tools


One of the major strengths of JavaScript is that it does not require expensive development
tools. You can start with a simple text editor such as Notepad. Since it is an interpreted
language inside the context of a web browser, you don't even need to buy a compiler.
To make our life simpler, various vendors have come up with very nice JavaScript editing tools.
Some of them are listed here
Microsoft FrontPage Microsoft has developed a popular HTML editor called
FrontPage. FrontPage also provides web developers with a number of JavaScript tools
to assist in the creation of interactive websites.
Macromedia Dreamweaver MX Macromedia Dreamweaver MX is a very popular
HTML and JavaScript editor in the professional web development crowd. It provides
several handy prebuilt JavaScript components, integrates well with databases, and
conforms to new standards such as XHTML and XML.
Macromedia HomeSite 5 HomeSite 5 is a well-liked HTML and JavaScript editor from
Macromedia that can be used to manage personal websites effectively.

1.6 Where is JavaScript Today?


The ECMAScript Edition 5 standard will be the first update to be released in over four years.
JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between
the two is extremely minor.

The specification for JavaScript 2.0 can be found on the following


site: http://www.ecmascript.org/
Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript standard,
although both the languages still support the features that are not a part of the standard.

Therefore, Javascript is a programming language that is used to enhance a website design. To


render a website in a better looking site.

All the modern browsers come with built-in support for JavaScript. Frequently, you may need
to enable or disable this support manually. This chapter explains the procedure of enabling
and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and
Opera.

3
JAVASCRIPT

1.6.1 JavaScript in Internet Explorer


Here are simple steps to turn on or turn off JavaScript in your Internet Explorer
Follow Tools Internet Options from the menu.
Select Security tab from the dialog box.
Click the Custom Level button.
Scroll down till you find the Scripting option.
Select Enable radio button under Active scripting.
Finally, click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select the Disable radio
button under Active scripting.

1.6.2 JavaScript in Firefox


Here are the steps to turn on or turn off JavaScript in Firefox
Open a new tab type about: config in the address bar.
Then you will find the warning dialog. Select Ill be careful, I promise!
Then you will find the list of configure options in the browser.
In the search bar, type javascript.enabled.
There you will find the option to enable or disable javascript by right-clicking on the
value of that option select toggle.
If javascript.enabled is true; it converts to false upon clickingtoogle. If javascript is disabled; it
gets enabled upon clicking toggle.

1.6.3 JavaScript in Chrome


Here are the steps to turn on or turn off JavaScript in Chrome
Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
Click Show advanced settings at the end of the page.
Under the Privacy section, click the Content settings button.
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all
sites to run JavaScript (recommended)".

4
JAVASCRIPT

1.6.4 JavaScript in Opera


Here are the steps to turn on or turn off JavaScript in Opera
Follow Tools Preferences from the menu.
Select Advanced option from the dialog box.
Select Content from the listed items.
Select Enable JavaScript checkbox.
Finally, click OK and come out.
To disable JavaScript support in your Opera, you should not select the Enable JavaScript
checkbox.

Warning for Non-JavaScript Browsers


If you have to do something important using JavaScript, then you can display a warning
message to the user using<noscript> tags.
You can add a noscript block immediately after the script block as follows

<html>
<body>

<script language="javascript" type="text/javascript">


<!--
document.write("Hello World!")
//-->
</script>

<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>

</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the
message from </noscript> will be displayed on the screen.

1.6.5 Why study Javascript?


JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

5
JAVASCRIPT

1.7 Excercise
Try the first javascript code in your text editor.

<html>
<body>

<script language="javascript" type="text/javascript">


<!--
document.write("Hello World!")
//-->
</script>

</body>
</html>

1) To run the program, write down the code from above.


2) Follow by saving the file in .html
3) Run the file with open with browser (internet explorer, chrome or firefox)

6
JAVASCRIPT

LESSON 2 JAVASCRIPT SYNTAX


2.1 Introduction
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>

The script tag takes two important attributes


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".

2.2 Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can
use spaces, tabs, and newlines freely in your program and you are free to format and indent
your programs in a neat and consistent way that makes the code easy to read and
understand.

7
JAVASCRIPT

2.3 Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just as they
are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your
statements is placed on a separate line. For example, the following code could be written
without semicolons.

<script language="javascript" type="text/javascript">


<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons

<script language="javascript" type="text/javascript">


<!--
var1 = 10; var2 = 20;
//-->
</script>
Note It is a good programming practice to use semicolons.

2.4 Case Sensitivity


JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization
of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE Care should be taken while writing variable and function names in JavaScript.

2.5 Comments in JavaScript


JavaScript support both C-style and C++-style comments, Thus
Any text between a // and the end of a line is treated as a comment and is ignored
by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it should
be written as //-->.

8
JAVASCRIPT

2.5.1 Example
The following example shows how to use comments in JavaScript.

<script language="javascript" type="text/javascript">


<!--

// This is a comment. It is similar to comments in C++

/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/

//-->
</script>

There is a flexibility given, to include JavaScript code anywhere in an HTML document.


However the most preferred ways to include JavaScript in an HTML file are as follows
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.

2.6 JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows

<html>

<head>

<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>

</head>

<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>

</html>

9
JAVASCRIPT

2.7 JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, you would not have
any function defined using JavaScript. Take a look at the following code.

<html>

<head>
</head>

<body>

<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<p>This is web page body </p>

</body>
</html>

2.8 JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>
</html>

10
JAVASCRIPT

2.9 JavaScript in External File


As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it
into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.

<html>

<head>
<script type="text/javascript" src="filename.js" ></script>
</head>

<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.jsfile and then you can
use sayHello function in your HTML file after including the filename.js file.

function sayHello() {
alert("Hello World")
}

2.10 Exercise
1) State the types of method to include javascript in the HTML code.
2) Please write down the methods of using javascript.

11
JAVASCRIPT

LESSON 3 CHANGING CONTENT


3.1 JavaScript Can Change HTML Content
One of many HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

Example
document.getElementById("demo").innerHTML = "Hello JavaScript";

3.2 JavaScript Can Change HTML Attributes


This example changes an HTML image, by changing the src attribute of an <img> tag:
It can change the light bulb color without reloading the page.

12
JAVASCRIPT

This is the sample code, within the <html> tag


<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Change Images</h1>

<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light.</p>

<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>

</body>
</html>

If you have css knowledge, it could change css element too.


Changing the style of an HTML element, is a variant of changing an HTML attribute:
document.getElementById("demo").style.fontSize = "25px";

Write this code down to see the demo:


<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>

<button type="button" onclick="myFunction()">Click Me!</button>

</body>
</html>

13
JAVASCRIPT

This is the outcome of the code when executed.

When you click on the click me! button, a line of red sentence will display without loading,
this is the usefulness of javascript.
Besides, Javascript can validate data.

JavaScript is often used to validate input:


<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Validate Input</h1>

<p>Please input a number between 1 and 10:</p>

<input id="numb" type="number">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
var x, text;

// Get the value of the input field with id="numb"


x = document.getElementById("numb").value;

14
JAVASCRIPT

// If x is Not a Number or less than one or greater than 10


if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

15
JAVASCRIPT

3.3 JavaScript Display Possibilities


JavaScript can "display" data in different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().

3.4 Using window.alert()


You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

3.5 Using document.write()


For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

16
JAVASCRIPT

Using document.write() after an HTML document is fully loaded, will delete all existing HTML:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

3.6 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:
<!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>

3.7 Using console.log()


In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html>

17
JAVASCRIPT

3.8 Exercise
1. Create a code that can produce a change of picture from red to yellow.
2. Validate a number from 10 to 20 using javascript validation code.

18
JAVASCRIPT

LESSON 4 JAVASCRIPT STATEMENTS AND FUNCTIONS


In HTML, JavaScript statements are "instructions" to be "executed" by the web browser.

4.1 JavaScript Statements


This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
<!DOCTYPE html>
<html>
<body>

<p>In HTML, JavaScript statements are "commands" to the browser.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

</body>
</html>

4.2 JavaScript Programs


A computer program is a list of "instructions" to be "executed" by the computer. In a
programming language, these program instructions are called statements. JavaScript is
a programming language. JavaScript statements are separated by semicolons.

19
JAVASCRIPT

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Statements</h1>

<p>Statements are separated by semicolons.</p>

<p>The variables x, y, and z are assigned the values 5, 6, and 11:</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript statements are composed of:


Values, Operators, Expressions, Keywords, and Comments.

4.3 JavaScript Values


The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.

4.4 JavaScript Literals


The most important rules for writing fixed values are:
Numbers are written with or without decimals;
Strings are text, written within double or single quotes
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>

<p>Number can be written with or without decimals.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

</body>
</html>

20
JAVASCRIPT

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>

<p>Strings can be written with double or single quotes.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

</body>
</html>

21
JAVASCRIPT

4.5 JavaScript Variables


JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

22
JAVASCRIPT

4.6 Much Like Algebra


In this example, price1, price2, and total, are variables:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p id="demo"></p>
<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>
</body>
</html>

23
JAVASCRIPT

4.7 JavaScript Data Types


JavaScript variables can hold numbers like 100, and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put quotes around a number, it will be treated as a text string.
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Strings are written with quotes.</p>


<p>Numbers are written without quotes.</p>
<p>Try to experiment with the // comments.</p>

<p id="demo"></p>

<script>
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

//document.getElementById("demo").innerHTML = pi;
document.getElementById("demo").innerHTML = person;
//document.getElementById("demo").innerHTML = answer;
</script>

</body>
</html>

24
JAVASCRIPT

LESSON 5 JAVASCRIPT OPERATOR


5.1 Introduction
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>x = 5, y = 2, calculate z = x + y, and display z:</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

25
JAVASCRIPT

Assignment operators assign values to JavaScript variables.

Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

The assignment operator (=) assigns a value to a variable.

JavaScript supports the following arithmetic operators


Assume variable A holds 10 and variable B holds 20, then

Sr.No Operator and Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30

2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10

3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200

4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

Note Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

26
JAVASCRIPT

5.2 Exercise
The following code shows how to use arithmetic operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);

b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>

27
JAVASCRIPT

Output:

a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
Set the variables to different values and then try...

28
JAVASCRIPT

LESSON 6 SIMPLE JQUERY


6.1 What is jQuery?
jQuery is a JavaScript Library
jQuery greatly simplifies JavaScript programming
jQuery is easy to learn

jQuery is a lightweight, "write less, do more", JavaScript library.


The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Tip: In addition, jQuery has plugins for almost any task out there.

6.2 Adding jQuery to Your Web Pages


There are several ways to start using jQuery on your web site. You can:
Download the jQuery library from jQuery.com
Include jQuery from a CDN, like Google

6.2.1 Downloading jQuery


There are two versions of jQuery available for downloading:
Production version - this is for your live website because it has been minified and
compressed
Development version - this is for testing and development (uncompressed and
readable code)

29
JAVASCRIPT

Both versions can be downloaded from jQuery.com.


The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-1.11.3.min.js"></script>
</head>
Tip: Place the downloaded file in the same directory as the pages where you wish to use it.

Do you wonder why we do not have type="text/javascript" inside the <script> tag?

This is not required in HTML5. JavaScript is the default scripting language in HTML5 and in all
modern browsers!

6.2.2 jQuery CDN


If you don't want to download and host jQuery yourself, you can include it from a CDN (Content
Delivery Network).
Both Google and Microsoft host jQuery.

To use jQuery from Google or Microsoft, use one of the following:


Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

Microsoft CDN:
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head>

jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and performing some action on
the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)

30
JAVASCRIPT

Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

Are you familiar with CSS selectors?

jQuery uses CSS syntax to select elements. You will learn more about the selector syntax in the
next chapter of this tutorial.

The Document Ready Event


You might have noticed that all jQuery methods in our examples, are inside a document
ready event:

$(document).ready(function(){

// jQuery methods go here...

});

This is to prevent any jQuery code from running before the document is finished loading (is
ready).
It is good practice to wait for the document to be fully loaded and ready before working with
it. This also allows you to have your JavaScript code before the body of your document, in the
head section.

Here are some examples of actions that can fail if methods are run before the document is fully
loaded:
Trying to hide an element that is not created yet
Trying to get the size of an image that is not loaded yet
Tip: The jQuery team has also created an even shorter method for the document ready event:
$(function(){

// jQuery methods go here...

});

Use the syntax you prefer. We think that the document ready event is easier to understand
when reading the code.

31
JAVASCRIPT

6.3 jQuery hide() and show()


With jQuery, you can hide and show HTML elements with the hide() and show() methods:
$("#hide").click(function(){
$("p").hide();
});

$("#show").click(function(){
$("p").show();
});

Sample code to follow:


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>

</body>
</html>

32
JAVASCRIPT

If you click on the hide the sentence will hide away.

When you click on show, the sentence will appear.

Syntax:
$(selector).hide(speed,callback);
$(selector).show(speed,callback);

The optional speed parameter specifies the speed of the hiding/showing, and can take the
following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the hide() or show()
method completes (you will learn more about callback functions in a later chapter).

The following example demonstrates the speed parameter with hide(). By following the code
below, you can see the speed of hiding the sentence:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>

<button>Toggle</button>

<p>This is a paragraph with little content.</p>


<p>This is another small paragraph.</p>

</body>
</html>

33
JAVASCRIPT

6.4 jQuery toggle()


With jQuery, you can toggle between the hide() and show() methods with the toggle()
method.

Shown elements are hidden and hidden elements are shown:


$("button").click(function(){
$("p").toggle();
});

Following the code below:


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>

<button>Toggle</button>

<p>This is a paragraph with little content.</p>


<p>This is another small paragraph.</p>

</body>
</html>

Before clicking on the toggle button

34
JAVASCRIPT

After clicking on the toggle button

6.5 Exercise
1. Run your own jQuery file
2. Then run a simple hide and show program just like what u have learnt just now.

35

You might also like