[Go to site: main page, start]

0% found this document useful (0 votes)
19 views114 pages

JavaScript and jQuery Basics Guide

Uploaded by

rutujatikhole
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views114 pages

JavaScript and jQuery Basics Guide

Uploaded by

rutujatikhole
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

UNIT – II

WEB SCRIPTING LANGUAGES


Outlin
e
JavaScript: Overview of JavaScript, using JS in an HTML
(Embedded, External), Data types, Control Structures,
Arrays, Functions and Scopes, Objects in JS,

DOM: DOM levels, DOM Objects and their properties and


methods, Manipulating DOM,

JQuery: Introduction to JQuery, Loading JQuery, Selecting


elements, changing styles, creating elements, appending
elements, removing elements, handling events.
Outlin
e
JavaScript: Overview of JavaScript, using JS in an HTML
(Embedded, External), Data types, Control Structures,
Arrays, Functions and Scopes, Objects in JS,

DOM: DOM levels, DOM Objects and their properties and


methods, Manipulating DOM,

JQuery: Introduction to JQuery, Loading JQuery, Selecting


elements, changing styles, creating elements, appending
elements, removing elements, handling events.
JavaScript-
Outline
• Overview of JavaScript,
• using JS in an HTML (Embedded, External),
• Data types,
• Control Structures,
• Arrays,
• Functions
• Objects
• Scopes
JavaScript – Introduction

● A programming language designed for web pages


● It is embedded directly into HTML Pages
● An interpreted, client-side, event based language
● It is dynamic, lightweight and case-sensitive

5
Overview of
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
• JavaScript is a very powerful client-side scripting language.
• client side scripting is a process in which scripts are
executed by browsers without connecting the server.
• Javascript is a dynamic computer programming language.

Example
Client-Side
Script
When  client makes the request, the HTML and all
scripts will be downloaded into your browser and then
the resultant HTML will be displayed in the browser is
called client-side script.

Example: JavaScript, VB-Script etc.


How Website Works
JavaScript
• JavaScript is a front-end scripting language developed by
Netscape for dynamic content
• Lightweight, but with limited capabilities

6
• Can be used as object-oriented language
• Client-side technology
• Embedded in your HTML page
• Interpreted by the Web browser
• Simple and flexible
• Powerful to manipulate the DOM
JavaScript
Advantages
• JavaScript allows interactivity such as:
• Implementing form validation
• React to user actions, e.g. handle keys

7
• Changing an image on moving mouse over it
• Sections of a page appearing and disappearing
• Content loading and changing dynamically
• Performing complex calculations
• Custom HTML controls, e.g. scrollable table
• Implementing AJAX functionality
What Can JavaScript
•Do?
Can handle events
• Can read and write HTML elements
• Can validate form data
• Can access / modify browser cookies

8
• Can detect the user’s browser and OS
• Can be used as object-oriented language
• Can handle exceptions
• Can perform asynchronous server calls (AJAX)
The JavaScript
Synta
x
JavaScript
Syntax
• JavaScript can be implemented using <script>... </script> HTML tags
in a web page.
• Place the <script> tags, within the <head> tags.

• Syntax:
<script language="javascript" type="text/javascript">
//JavaScript code
</script>
JavaScript Editor and
Extension
Use Notepad to write the code

Save the document using .html (if embedded


JavaScript)

Save document with .js (if external


JavaScript)

Run the code in brower


Inline JavaScript
You can write JavaScript code directly inside the HTML element using the onclick,
onmouseover, or other event handler attributes.

<html>
AI Generated
<head></head>
code with ZZZ
<body>
<h2>
Adding JavaScript in HTML Document
</h2>
<button Clicked!')">
Click Here
</button>
</html>
JavaScript
Syntax
• Example:
<html>
<body>
<script language="javascript" type="text/javascript">
[Link]("Hello World!")
</script>
</body>
</html>
• JS Embedded in HTML Output
Hello World!

External JS
JavaScript
Syntax
• The JavaScript syntax is similar to C# and Java
• Operators (+, *, =, !=, &&, ++, …)
• Variables (typeless)
• Conditional statements (if, else)

12
• Loops (for, while)
• Arrays (my_array[]) and associative arrays (my_array['abc'])
• Functions (can return value)
• Function variables (like the C# delegates)
Enabling JavaScript
in Browsers
• JavaScript in Firefox
• Open a new tab → type about: config in the address bar.
• Then you will find the warning dialog.
• Select I’ll be careful, I promise!
• Then you will find the list of configure options in the browser.
• In the search bar, type [Link].
• There you will find the option to enable or disable javascript
by right-clicking on the value of that option → select toggle.
Naming Form Elements in HTML
<form name="addressform">

<label for="yourname"> Name:</label>


<input type="text" id="yourname"
name="yourname"><br><br>

<label for="phone">Phone:</label>
<input type="tel" id="phone"
name="phone"><br><br>

Click Here <label for="email">Email:</label>


<input type="email" id="email"
name="email"><br><br> </form>
JavaScript - Placement
in HTML File
• 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.
JavaScript in <head>...</head>
section
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") }
//--> </script>
</head>
<body>
<input type="button" value="Say Hello" />
</body>
</html>

• This code will produce the following results −


JavaScript in <body>...</body>
section
<html>
<head> </head>
<body>
<script type="text/javascript">
<!--
[Link]("Hello World")
//-->
</script>
<p>This is web page body </p>
</body> See Demo
</html>

• This code will produce the following results −


Hello World
This is web page body
JavaScript in <body> and
<head>
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") } //-->
</script>
</head>
<body>
<script type="text/javascript">
<!-- [Link]("Hello World") //-->
</script>
<input type="button" value="Say Hello" />
</body> </html>

• This code will produce the following result −


JavaScript in External
File
• HTML File
<html>
<head>
<script type="text/javascript" src="[Link]" >
</script>
</head>
<body> ....... </body>
</html>
• JavaScript File – [Link]
function sayHello()
{ alert("Hello World") }

Another Example- Feedback


The First
Script
[Link]
<html>

<body>
<script

20
type="text/javascript">
alert('Hello
JavaScript!');
</script>
</body>

</html>
Another Small
Example
[Link]
<html>

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

21
[Link]('JavaScript
rulez!');
</script>
</body>

</html>
Using JavaScript
Code
• The JavaScript code can be placed in:
• <script> tag in the head
• <script> tag in the body – not recommended
• External files, linked via <script> tag the head

22
• Files usually have .js extension
• Highly recommended
• The .js files get cached by the browser

<script src="[Link]"
type="text/javscript">
<!– code placed here will not be executed!
-->
</script>
JavaScript – When is
•Executed?
JavaScript code is executed during the page loading or when the
browser fires an event
• All statements are executed at page loading
• Some statements just define functions that can be called later

23
• Function calls or code can be attached as "event handlers" via tag
attributes
• Executed when the event is fired by the browser

<img src="[Link]"
/>
Calling a JavaScript Function
from Event Handler – Example
<html> [Link]
<head>
<script
type="text/javascript">

24
function test (message)
{
alert(message);
}
</script>
</head>
<body>
<img src="[Link]"
> />
</body>
</html>
Using External Script
Files
• Using external script files:
<html [Link]
>
<script src="[Link]"
<head
> type="text/javascript">
</</script> The <script> tag is always empty.

25
head>
<body>
<button value="Call
JavaScript function from [Link]" />
</body>
</html>
• External JavaScript file:
function sample() {
alert('Hello from
[Link]!')
} sample.j
s
Assignment
Create a Registration form for Elective subjects

Output
Assignment
1. Write a JavaScript program that asks the user for their age and then prints out
a message indicating whether they are eligible to vote or not

See the code


Data
•Types
JavaScript data types:
• Numbers (integer, floating-point)
• Boolean (true / false)
• String type – string of characters

26
var myName = "Pradnya”
[Link]("Hello",myName)
Output: Hello Pradnya

var my_array = [1, 5.3, "aaa"];


Output: [Link](my_array);VM299:1 (3) [1, 5.3, 'aaa']

• Associative arrays (hash tables)


var my_hash = {a:2, b:3,
c:"text"};
Everything is
•Object
Every variable can be considered as object
• For example strings and arrays have member functions:
[Link]

27
let test = "some string";
alert(test[7]); // shows letter
'r'
alert([Link](5)); // shows letter
's' alert("test".charAt(2)); //shows
letter 'e'
alert("test".substring(1,3));
var arr = [1,3,4]; //shows
'es'
alert ([Link]); // shows 3
[Link](7); // appends 7 to end of
array alert (arr[1]); // shows 7
String
Operations
• The + operator joins
strings
string1 = "fat ";
string2 = "cats";
alert(string1 + // fat

28
string2); cats
• What is "9" + 9?
alert("9" + //
9); 99
• Converting string to number:
alert(parseInt("9") + //
9); 18
Arrays Operations and
Properties
•Declaring new empty array:
var arr = new Array();
•Declaring an array holding few elements:
var arr = [1, 2, 3, 4, 5];

29
•Appending an element / getting the last element:
[Link](3);
var element = [Link]();
•Reading the number of elements (array length):
[Link];
•Finding element's index in the array:
[Link](1);
var arr = [1, 2, 3, 4, 5];
[Link](3); // Add 3 to the end of the array
var element = [Link](); // Remove the last element and store it in 'element'

// Display the array and the value of 'element' in the console


[Link]("Array:", arr); // Display the updated array
[Link]("Popped Element:", element); // Display the removed element

Output:
Array: [1, 2, 3, 4, 5]
Popped Element: 3
Standard Popup
•Boxes
Alert box with text and [OK] button
• Just a message shown in a dialog box:
alert("Some text here");

30
• Confirmation box
• Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");

• Prompt box
• Contains text, input field with default value:

prompt ("enter amount", 10);


JavaScript
Variables
<script type="text/javascript">

var name = "Ali"; var money; money =


2000.50;

</script>
Sum of Numbers –
[Link]
Example
<html>

<head>
<title>JavaScript Demo</title>

32
<script type="text/javascript">
function calcSum()
{ value1 =
parseInt([Link]
ue); value2 =
parseInt([Link]
ue); sum = value1 + value2;
[Link] = sum;
}
</script>
</head>
Sum of Numbers – Example
[Link]
(2)
(cont.)
<body>
<form name="mainForm">
<input type="text" name="textBox1" />
<br/>

33
<input type="text" name="textBox2" />
<br/>
<input type="button" value="Process"
calcSum()" />
<input type="text"
name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
JavaScript Prompt –
Example
[Link]
price = prompt("Enter the price",
"10.00"); alert('Price + VAT = ' +
price * 1.2);

34
JavaScript -
Operators
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Questions to solve
1. Create a JavaScript object that represents a
person with properties name, age, and city. Then,
print out the values of these properties to the
console
2. Create a JavaScript array that contains a mix of
data types (e.g. numbers, strings, booleans). Then,
print out the values of the array to the console.
3. Write a JavaScript program that uses the prompt()
function to ask the user for their name and then
prints out a greeting message with the user's
name.
Conditional Statement
(if)
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}

36
Symbol Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal
!= Not equal
Solve
Create a JavaScript function that takes a grade as an
input and prints out a message indicating whether
the grade is passing or failing.
function checkGrade(grade) {
if (grade >= 50) {
[Link]("Passing grade!");
} else {
[Link]("Failing grade.");
}
}

// Example usage:
checkGrade(75); // Output: Passing grade!
checkGrade(45); // Output: Failing grade.
Switch
Statement
• The switch statement works like in
C#:
switch (variable) [Link]
{ case 1:
// do something

37
break;
case 'a':
// do something
else
break;
case
3.14:
// another
code break; completely
// something
default:
different
}
Switch case
Example
Loop
s• Like in C#
• for loop
• while loop

39
• do … while
loop
var counter;
for (counter=0; counter<4;
counter++)
{
alert(counter);
}
while (counter < 5)
{
[Link]
alert(++counter);
While-loop
Example
• <!DOCTYPE html>
• <html>
• <head>
• <title>While Loop Example</title>
• </head>
• <body> <script type="text/javascript">
• var count = 0;
• [Link]("Starting Loop<br />");
• while (count < 10)
• { [Link]("Current Count : " + count + "<br />");
• count++; }
• [Link]("Loop stopped!");
• </script>
• </body>
• </html>
Assignment
1. Write a JavaScript program that uses a
switch statement to print out a message
based on the day of the week.
2. Create a JavaScript loop that prints out the
numbers from 1 to 10 using a while loop.
3. Write a JavaScript program that uses a for-
in loop to iterate over the properties of an
object and print out their values.
Functions
• Code structure – splitting code into parts
• Data comes in, processed, result returned

Parameters come in

41
here.

Declaring variables
is optional. Type is
never declared.

Value returned
here.
Function Arguments & Return
Value
• Functions are not required to return a value
• When calling function it is not obligatory to specify all of its arguments
• The function has access to all the arguments passed
via arguments array

42
JavaScript Function
Syntax
• function name(parameter1, parameter2, parameter3) {
code to be executed
}

• var x = myFunction(4, 3); // Function is called, return


value will end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of a
and b
}
????
1. Write a JavaScript program that uses a function to
calculate the area of a rectangle.
2. Create a JavaScript function that takes a string as input
and returns the string with all vowels removed.
3. Write a JavaScript program that uses a function to
determine whether a number is prime or not.
4. Create a JavaScript function that takes an array as input
and returns the array with all duplicates removed.
Introduction to ES6
[Link]

Arrow Functions

// Regular function function add(a, b)


{ return a + b;}// Arrow function with a different name
const addArrow = (a, b) => a + b;
[Link](add(5, 3)); // Output: 8
[Link](addArrow(10, 20)); // Output: 30

Note: In JavaScript, you cannot declare the same variable name more than
once using let or const in the same scope.
Outlin
e
JavaScript: Overview of JavaScript, using JS in an HTML
(Embedded, External), Data types, Control Structures,
Arrays, Functions and Scopes, Objects in JS,

DOM: DOM levels, DOM Objects and their properties and


methods, Manipulating DOM,

JQuery: Introduction to JQuery, Loading JQuery, Selecting


elements, changing styles, creating elements, appending
elements, removing elements, handling events.
HTML
• Adds structure to our web pages
• Tags used for e.g. <p>, <div>, <section>

CSS
• Adds styles to website
• e.g. color, border, margin, image, position, etc
• Can use ids, classes or direct tags to refer HTML tags

JAVASCRIPT
• It adds programming to our web pages
• Adds Functionality
• e.g. client side validation, effects and events
What is the
DOM?
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:

• The W3C DOM standard is separated into 3 different parts:


1. Core DOM - standard model for all document types
2. XML DOM - standard model for XML documents
3. HTML DOM - standard model for HTML documents
Document Object Model
• DOM (Document Object Model) is a programming
interface for web documents
• It represents the structure of an HTML or XML document
as a tree of objects.
• allowing programs to interact with, modify, and update the
content, structure, and style dynamically.
DOM- Document Object
Mode
• When a web page is loaded, the browser creates a Document
Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects:
HTML and DOM
Benefits of DOM to
JavaScript
• With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
DOM
Levels
• DOM Level 1
• DOM Level 2
• DOM Level 3
DOM Level 0 (Legacy DOM)
 used in Netscape Navigator 2 and Internet Explorer 3.

 a collection of predefined objects (like document, window,


forms, images) that allowed limited interaction with
elements

 It did not provide full access to the document structure.


Example DOM Level 0
<!DOCTYPE html>
<html>
<head>
<title>DOM Level 0 Example</title>
</head>
<body>
<button Me</button>
</body>
</html>
DOM Level
1• better document structure and scripting capabilities.
Levels

Core HTML

access and manipulate XML and methods and properties specifically


HTML documents. for handling HTML documents.
Core DOM way for programming languages like JavaScript to
interact with, modify, and manipulate documents dynamically.

 Each HTML or XML element is a node.


 Attributes and text inside elements are child nodes.
 The entire document is represented as the root node.

Example:
Tree structure
<!DOCTYPE html>
Document
<html>
├── <html>
<head>
│ ├── <head>
<title>Core DOM Example</title>
│ │ ├── <title> → "Core DOM Example"
</head>
│ ├── <body>
<body>
│ │ ├── <h1> → "Hello, World!"
<h1>Hello, World!</h1>
</body>
</html>
Types of Nodes in Core DOM
1. Document Node
 entire document.
 root node of the DOM tree.
 Example: document
2. Element Node
 Represents HTML or XML elements.
 Example: <h1>, <p>, <div>, <body>
3. Attribute Node
 Represents attributes of an element.
 Example: id="heading", class="text“
4. Text Node
 Represents the text inside an element.
 Example: The text "Hello, World!" inside <h1>Hello, World!</h1>
Core DOM Methods
1. Accessing Elements
• getElementById(id) → Selects an element by its ID.
• getElementsByTagName(tag) → Selects all elements with a
given tag name.
• getElementsByClassName(class) → Selects elements by
their class name.
• querySelector(selector) → Selects the first element
matching a CSS selector.
• querySelectorAll(selector) → Selects all elements matching
a CSS selector.
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="heading">Hello, World!</h1>
<script>
var element = [Link]("heading");
[Link]([Link]); // Output: Hello, World!
</script>
</body>
</html>
2. Modifying Elements
innerHTML → Changes the HTML inside an element.
setAttribute(name, value) → Modifies
an attribute of an element.
createElement(tag) → Creates a new element.
appendChild(node) → Adds a new child to an element.
3. Creating and Adding Elements
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
<script>
var newElement = [Link]("p"); // Create <p> element
[Link] = "This is a new paragraph!"; // Add text
[Link]("container").
appendChild(newElement); // Add it to the div
</script>
</body>
</html>
Structure of HTML DOM Level 1
 Each element is a node.
 Text inside elements is a child node.
 Attributes are associated with elements but not part of the
child nodes.
Tree
<!DOCTYPE html> Document
<html> ├── <html>
<head> │ ├── <head>
<title>DOM Level 1 Example</title> │ │ ├── <title> → "DOM Level 1 Example"
</head> │ ├── <body>
<body> │ │ ├── <h1 id="heading"> → "Hello,
<h1 id="heading">Hello, World!</h1> World!"
</body>
</html>
1. Accessing Elements

Method Description
[Link]("id") Selects an element by its id.
Selects elements by their
[Link]("tag") tag name.
Selects elements by their
[Link]("class")
class name.
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello, DOM Level 1!</h1>
<script>
var element = [Link]("title");
[Link]([Link]); // Output: Hello, DOM Level 1!
</script>
</body>
</html>

Output:
Hello, DOM Level 1!
2. Modifying Elements
Method Description
innerHTML Modifies the content inside an element..
Modifies an attribute of an element.
setAttribute(name, value)

Refer slide no 73 Eg.


3. Handling Events
Runs a function when the element is clicked."
DOM Level
1• The DOM Level 1 specification is separated into two parts:
1. Core and
2. HTML.
• Core Level 1 provides a low-level set of fundamental
interfaces that can represent any structured document, as
well as defining extended interfaces for representing an XML
document.
• HTML Level 1 provides additional, higher-level interfaces that
are used with the fundamental interfaces defined in Core
Level 1 to provide a more convenient view of an HTML
document. Interfaces introduced in DOM1 include, among
others, the Document, Node, Attr, Element, and Text
interfaces.
DOM Level 2 (Enhanced Features)

•Introduced in 2000, DOM Level 2 added support for:


•Events (addEventListener, removeEventListener)
•Style manipulation (getComputedStyle)
•Namespace support for XML documents.
It allowed more dynamic interaction with HTML and XML
documents.
Example
DOM Level
2• The DOM Level 2 specification contains six different
specifications:
• The DOM2 Core,
• Views,
• Events,
• Style,
• Traversal and Range, and
• the DOM2 HTML. Most of the DOM Level 2 is supported in
Mozilla.
DOM Level
2
Specification Description
helps the programs and scripts to access and update
DOM Level 2 Core the content and structure of document dynamically
allows programs and scripts to dynamically access and
DOM Level 2 Views update the content of an HTML or XML document
provides a generic event system to programs and
DOM Level 2 Events scripts
allows programs and scripts to dynamically access and
DOM Level 2 Style update the content of style sheets
DOM Level 2 Traversal allows programs and scripts to dynamically traverse
and Range and identify a range of content in a document
allows programs and scripts to dynamically access and
DOM Level 2 HTML update the content and structure of HTML 4.01 and
XHTML 1.0 documents
DOM Level
3• The DOM Level 3 specification contains five different
specifications:
• The DOM3 Core,
• Load and Save,
• Validation,
• Events, and
• XPath.
DOM Level 3 (Advanced Capabilities)

 Introduced in 2004, DOM Level 3 added:


• Better XML handling (DOM Load and Save)
• Support for XPath and validation of documents.
• Enhanced event handling.
Example
DOM Level
3
Specification Description
allows programs and scripts to dynamically access and
DOM Level 3 Core update the content, structure, and document style
DOM Level 3 Load allows programs and scripts to dynamically load the
and Save content of an XML document into a DOM document
allows programs and scripts to dynamically update the
DOM Level 3 content and structure of documents and ensures that
Validation the document remains valid
DOM Objects and their
properties and
methods
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of
each object.
• HTML DOM properties are values (of HTML Elements) that
you can set or change.
• HTML DOM methods are actions you can perform (on HTML
Elements). A method is an action you can do (like add or
deleting an HTML element).
Finding HTML
Elements
Method Description
[Link](id) Find an element by element id
[Link](name) Find elements by tag name
[Link](name) Find elements by class name
Adding and Deleting
Elements
Method Description
[Link](element) Create an HTML element
[Link](element) Remove an HTML element
[Link](element) Add an HTML element
[Link](element) Replace an HTML element
[Link](text) Write into the HTML output stream
Adding Events
Handlers
Method Description

[Link](id).onclick Adding event

= function(){code} handler code to an


onclick event
Finding HTML
Objects
Property Description DOM
Returns the absolute base URI of the
[Link] document 3

[Link] Returns the <body> element 1


[Link] Returns the document's cookie 1
[Link] Returns the document's doctype 3
[Link] Returns all <form> elements 1
[Link] Returns the <head> element 3
[Link] Returns all <img> elements 1
Changing HTML
Content
• Example
<html> <body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body> </html>

• Output
JavaScript can Change HTML
New text!
The paragraph above was changed by a script.
Changing the Value of an
Attribute
• Example
<html><body>
<img id="image" src="[Link]" width="160" height="120">
<script>
[Link]("image").src = "[Link]";
</script>
<p>The original image was [Link], but the script changed it to
[Link]</p>
</body></html>

• Output
Outlin
e
JavaScript: Overview of JavaScript, using JS in an HTML
(Embedded, External), Data types, Control Structures,
Arrays, Functions and Scopes, Objects in JS,

DOM: DOM levels, DOM Objects and their properties and


methods, Manipulating DOM,

JQuery: Introduction to JQuery, Loading JQuery, Selecting


elements, changing styles, creating elements, appending
elements, removing elements, handling events.
jQuery -
Introduction
• jQuery is a JavaScript Library.
• jQuery greatly simplifies JavaScript programming.
• jQuery is a lightweight
• 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
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 [Link]
• Include jQuery from a CDN, like Google
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
• Both versions can be downloaded from [Link].
• 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="[Link]"></script>
</head>
• Tip: Place the downloaded file in the same directory as the
pages where you wish to use it.
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="[Link]
</script>
</head>
jQuery
Syntax
• With jQuery you select (query) HTML elements and perform
"actions" on them.
• syntax :
• $(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)
• 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".
jQuery Selectors-
Selecting elements
• jQuery selectors allow you to select and manipulate HTML
element(s).
• jQuery selectors are used to "find" (or select) HTML elements
based on their name, id, classes, types, attributes, values of
attributes and much more. It's based on the existing CSS
Selectors, and in addition, it has some own custom selectors.
• All selectors in jQuery start with the dollar sign and
parentheses: $().
The element
Selector
• The jQuery element selector selects elements based on the
element name.
• You can select all <p> elements on a page like this:
• $("p")
• Example
• When a user clicks on a button, all <p> elements will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
}); Run : [Link]
The #id
Selector
• The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element.
• An id should be unique within a page, so you should use the #id
selector when you want to find a single, unique element.
• To find an element with a specific id, write a hash character,
followed by the id of the HTML element:
• $("#test")
• Example
• When a user clicks on a button, the element with id="test" will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
}); Execute [Link]
jQuery css() Method- Changing
Style
•jQuery css() Method
• The css() method sets or returns one or more style
properties for the selected elements.
• Return a CSS Property
• To return the value of a specified CSS property, use the
following syntax:
• css("propertyname");
• Set a CSS Property
• To set a specified CSS property, use the following
syntax:
• css("propertyname","value");
Changing Style-
Return a CSS Property
Example
<html><head>
<script
src="[Link]
ript>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head><body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Return background-color of p</button>
</body></html> click:
Changing Style-
Return a CSS Property Example
o/p
Output of Previous Code
Changing Style-
Set a CSS Property
Example
<html><head> [Link]
<script
src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Set background-color of p</button>
</body></html>
Changing Style-
Set a CSS Property Example
o/p
Output of Previous Code

After clicking on button


jQuery - Add
Elements
• We will look at four jQuery methods that are used to add new
content:
• append() - Inserts content at the end of the selected
elements
• prepend() - Inserts content at the beginning of the
selected elements
• after() - Inserts content after the selected
elements
• before() - Inserts content before the selected
elements
jQuery append() Method- Exam
ple
<html><head>
<script
src="[Link]
t>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("ol").append("<li> List item 3 </li>");
}); }); </script>
</head>
<body> After Clicking on button
<ol>
<li>List item 1</li>
<li>List item 2</li>
</ol>
<button id="btn1"> Append list items </button>
</body></html>
jQuery - Remove Eleme
nts
• Remove Elements/Content
• To remove elements and content, there are mainly two jQuery
methods:
• remove() - Removes the selected element (and its
child elements)
• empty() - Removes the child elements from the
selected element
jQuery remove() Method-
Example
• <html > <head>
• <script src="[Link]
</script>
• </head>
• <body>
• <p>Hello</p>
• how are you?
• <button>Remove </button>
• <script> After Clicking on button
• $( "button" ).click(function() {
• $( "p" ).remove();
• });
• </script>
• </body></html>
References
• [Link]
k_guide.htm
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
sp
• [Link]
• [Link]

You might also like