JavaScript and jQuery Basics Guide
JavaScript and jQuery Basics Guide
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.
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
<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="phone">Phone:</label>
<input type="tel" id="phone"
name="phone"><br><br>
<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
26
var myName = "Pradnya”
[Link]("Hello",myName)
Output: Hello Pradnya
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'
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:
</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
}
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
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,
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:
Core HTML
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)
• 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,