0% found this document useful (0 votes)
24 views51 pages

JAVASCRIPT-MODULE 4 Full

JavaScript is a core web development language used to program the behavior of web pages, allowing for dynamic content updates and data manipulation. It includes features such as variables, data types, operators, control statements, and the Document Object Model (DOM) for interacting with HTML elements. Key functionalities include displaying data, modifying HTML and CSS, and handling user interactions through events.

Uploaded by

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

JAVASCRIPT-MODULE 4 Full

JavaScript is a core web development language used to program the behavior of web pages, allowing for dynamic content updates and data manipulation. It includes features such as variables, data types, operators, control statements, and the Document Object Model (DOM) for interacting with HTML elements. Key functionalities include displaying data, modifying HTML and CSS, and handling user interactions through events.

Uploaded by

srideep242n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

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

What is JavaScript?

JavaScript is the programming language of the web.

It can update and change both HTML and CSS.

It can calculate, manipulate and validate data.

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript in Body</h2>

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

<script>

//WRITE JAVASCRIPT CODE HERE

</script>

</body></html>
JavaScript Display Possibilities
JavaScript can "display" data in different ways:

●​ Writing into an HTML element, using innerHTML or innerText.


●​ Writing into the HTML output using document.write().
●​ Writing into an alert box, using window.alert().

1.Using innerHTML
To access an HTML element, you can use the document.getElementById(id) method.

Use the id attribute to identify the HTML element.

Then use the innerHTML property to change the HTML content of the HTML element:

2.Using innerText
To access an HTML element, use the document.getElementById(id) method.

Then use the innerText property to change the inner text of the HTML element:
3. Using document.write()
For testing purposes, it is convenient to use document.write()

Using document.write() after an HTML document is loaded, will delete all existing HTML:

4.Using window.alert()
You can use an alert box to display data:
5.JavaScript Print
JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to print the content
of the current window.
6. Using console.log()
console.log() method in the browser to display data.

Variables and Datatypes in JavaScript


Variables and data types are foundational concepts in programming, serving as the
building blocks for storing and manipulating information within a program.

Variables

A variable is like a container that holds data that can be reused or updated later in the
program. In JavaScript, variables are declared using the keywords var, let, or const.

1. var Keyword

The var keyword is used to declare a variable. It has a function-scoped or


globally-scoped behaviour.’

var n = 5;
console.log(n);

var n = 20; // reassigning is allowed

console.log(n);

Output

20

2. let Keyword

The let keyword has block scope and cannot be re-declared in the same scope.

let n= 10;

n = 20; // Value can be updated

// let n = 15; //can not redeclare

console.log(n)

Output

20
3. const Keyword

The const keyword declares variables that cannot be reassigned. It’s block-scoped as
well.

const n = 100;

// n = 200; This will throw an error

console.log(n)

Output

100

Data Types

JavaScript supports various datatypes, which can be broadly categorized into


primitive and non-primitive types.

Primitive Datatypes

Primitive datatypes represent single values and are immutable.

1. Number: Represents numeric values (integers and decimals).

let n = 42;

let pi = 3.14;

2. String: Represents text enclosed in single or double quotes.

let s = "Hello, World!";


3. Boolean: Represents a logical value (true or false).

let bool= true;

4. Undefined: A variable that has been declared but not assigned a value.

let notAssigned;

console.log(notAssigned);

Output

undefined

5. Null: Represents an intentional absence of any value.

let empty = null;

6. Symbol: Represents unique and immutable values, often used as object keys.

let sym = Symbol('unique');

7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.

let bigNumber = 123456789012345678901234567890n;

Non-Primitive Datatypes

Non-primitive types are objects and can store collections of data or more complex
entities.

1. Object: Represents key-value pairs.

let obj = { name: "Amit",age: 25};

2. Array: Represents an ordered list of values.

let a = ["red", "green", "blue"];


3. Function: Represents reusable blocks of code.

function fun() {

console.log("GeeksforGeeks");

JavaScript Objects
Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to an object named car:

Example

const car = {type:"Fiat", model:"500", color:"white"};

It is a common practice to declare objects with the const keyword.

JavaScript Operators
JavaScript operators are symbols or keywords used to perform operations on values
and variables. They are the building blocks of JavaScript expressions and can
manipulate data in various ways.

there are various operators supported by JavaScript.


1. JavaScript Arithmetic Operators

Arithmetic Operators perform mathematical calculations like addition, subtraction,


multiplication, etc.

const sum = 5 + 3; // Addition

const diff = 10 - 2; // Subtraction

const p = 4 * 2; // Multiplication

const q = 8 / 2; // Division

console.log(sum, diff, p, q );

Output

8884

●​ + adds two numbers.


●​ – subtracts the second number from the first.
●​ * multiplies two numbers.
●​ / divides the first number by the second.

2. JavaScript Assignment Operators

Assignment operators are used to assign values to variables. They can also perform
operations like addition or multiplication before assigning the value.
let n = 10;

n += 5;

n *= 2;

console.log(n);

Output

30

●​ = assigns a value to a variable.


●​ += adds and assigns the result to the variable.
●​ *= multiplies and assigns the result to the variable.

3. JavaScript Comparison Operators or relational operators

Comparison operators compare two values and return a boolean (true or false). They
are useful for making decisions in conditional statements.

console.log(10 > 5);

console.log(10 === "10");

Output

true
false

●​ > checks if the left value is greater than the right.


●​ === checks for strict equality (both type and value).
●​ Other operators include <, <=, >=, and !==.

4. JavaScript Logical Operators

Comparison operators are mainly used to perform the logical operations that
determine the equality or difference between the values.

const a = true, b = false;

console.log(a && b); // Logical AND

console.log(a || b); // Logical OR


Output

false

true

●​ && returns true if both operands are true.


●​ || returns true if at least one operand is true.
●​ ! negates the boolean value.

5. JavaScript Ternary Operator

The ternary operator is a shorthand for conditional statements. It takes three operands.

const age = 18;

const status = age >= 18 ? "Adult" : "Minor";

console.log(status);

Output

Adult

condition ? expression1 : expression2 evaluates expression1 if the condition is true,


otherwise evaluates expression2.
6. JavaScript Unary Operators

Unary operators operate on a single operand (e.g., increment, decrement).

let x = 5;

console.log(++x); // Pre-increment

console.log(x--); // Post-decrement (Output: 6, then x becomes 5)

Output

●​ ++ increments the value by 1.


●​ — decrements the value by 1.
●​ typeof returns the type of a variable.

7. JavaScript String Operators

JavaScript String Operators include concatenation (+) and concatenation assignment


(+=), used to join strings or combine strings with other data types.

const s = "Hello" + " " + "World";

console.log(s);
Output

Hello World

●​ + concatenates strings.
●​ += appends to an existing string.

Control Statements in JavaScript


(https://www.geeksforgeeks.org/conditional-statements-in-javascript/?ref=ml_lbp)

JavaScript control statement is used to control the execution of a program based on a


specific condition.

Types of Control Statements in JavaScript

●​ Conditional Statement: JavaScript conditional statements allow you to


execute specific blocks of code based on conditions. If the condition is
met, a particular block of code will run; otherwise, another block of code
will execute based on the condition. Different types of conditional
statements include if, if…else, else..if ladder, switch statements, ternary
operator.
●​ Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement
will keep repeating itself until and unless it is satisfied.

Conditional statements

1.If Statement
The if statement is used to evaluate a particular condition. If the condition holds true,
the associated code block is executed.

Syntax:

if ( condition_is_given_here ) {

// If the condition is met,

//the code will get executed.

Example: this javascript checks whether the number is positive or negative

Output: The number is positive

2: If-Else Statement

The if-else statement will perform some action for a specific condition. Here we are
using the else statement in which the else statement is written after the if statement
and it has no condition in their code block.

Syntax:

if (condition1) {
// Executes when condition1 is true

Else{

// Executes when condition 1 is false

Example:

3: if… else if Statement


The else if statement in JavaScript allows handling multiple possible conditions and
outputs, evaluating more than two options based on whether the conditions are true or
false.

Example
4: Switch Statement
As the number of conditions increases, you can use multiple else-if statements in
JavaScript. but when dealing with many conditions, the switch statement may be a
more preferred option.

Syntax:

switch (expression) {

case value1:

statement1;

break;

case value2:

statement2;

break;

.
case valueN:

statementN;

break;

default:

statementDefault;

Example:

5: Ternary Operator (Conditional Operator)

The conditional operator, also referred to as the ternary operator (?:), is a shortcut
for expressing conditional statements in JavaScript.
Syntax:

condition ? value if true : value if false

Example:Output

Loops or iterative statements

1.​ For loop

In this approach, we are using for loop in which the execution of a set of
instructions repeatedly until some condition evaluates and becomes false

Syntax:

for (statement 1; statement 2; statement 3) {

// Code here . . .

Example:
2.​ While loop

The while loop repeats a block of code as long as the condition is true.
3.​ JavaScript do...while loop

The do...while loop executes the block of code at least once before checking the
condition.
Document Object Model (DOM)
●​ The HTML DOM (Document Object Model) is a programming
interface that represents the structure of a web page in a way that
programming languages like JavaScript can understand and manipulate.
●​ 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 for the bellow
corresponding html code:

●​

●​

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

JavaScript HTML DOM Navigation


With the HTML DOM, you can navigate the node tree using node relationships.

DOM Nodes

everything in an HTML document is a node:

●​ The entire document is a document node


●​ Every HTML element is an element node
●​ The text inside HTML elements are text nodes
●​ Every HTML attribute is an attribute node (deprecated)
●​ All comments are comment nodes

With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.

New nodes can be created, and all nodes can be modified or deleted.

Node Relationships

The nodes in the node tree have a hierarchical relationship to each other.

The terms parent, child, and sibling are used to describe the relationships.

●​ In a node tree, the top node is called the root (or root node)
●​ Every node has exactly one parent, except the root (which has no parent)
●​ A node can have a number of children
●​ Siblings (brothers or sisters) are nodes with the same parent

Navigating Between Nodes

You can use the following node properties to navigate between nodes with
JavaScript:
●​ parentNode
●​ childNodes[nodenumber]
●​ firstChild
●​ lastChild
●​ nextSibling
●​ previousSibling

Example : Accessing the innerHTML property is the same as accessing the


nodeValue of the first child:

myTitle = document.getElementById("demo").firstChild.nodeValue;

Changing HTML Content using Javascript

The easiest way to modify the content of an HTML element is by using the
innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML


Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value


Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style

The following example changes the style of a <p> element:


JavaScript HTML DOM Elements
Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

●​ Finding HTML elements by id


●​ Finding HTML elements by tag name
●​ Finding HTML elements by class name
●​ Finding HTML elements by CSS selectors

a)​ Finding HTML Element by Id


The easiest way to find an HTML element in the DOM, is by using the element id. This example
finds the element with id="intro":

const element = document.getElementById("intro");


If the element is found, the method will return the element as an object (in element).If the element is
not found, element will contain null.

b)​Finding HTML Elements by Tag Name(html tag)


This example finds all <p> elements:

const element = document.getElementsByTagName("p");

c)​Finding HTML Elements by Class Name


If you want to find all HTML elements with the same class name, use getElementsByClassName().

This example returns a list of all elements with class="intro".

const x = document.getElementsByClassName("intro");
d)​Finding HTML Elements by CSS Selectors
If you want to find all HTML elements that match a specified CSS selector (id, class names,
types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".

const x = document.querySelectorAll("p.intro");

Remove(Delete) & Add(Create) new HTML Tags


using JavaScript
In web development, dynamically add or remove HTML tags using JavaScript

Using createElement
In this approach, we are using the createElement() method to dynamically add a new
HTML tag.

To add a new element to the HTML DOM, you must create the element (element node) first,
and then append it to an existing element.
The above code creates a new <p> element by createElement

To add text to the <p> element, you must create a text node first. This code creates a text node using
createTextNode

Then you must append the text node to the <p> element using appendChild

Finally you must append the new element to an existing element. This code finds an existing element
by getElementById

This code appends the new element to the existing element by appendChild

Removing Existing HTML Elements


●​ To remove an HTML element, use the remove() method:
The above HTML document contains two <p> elements

Find the element you want to remove using getElementById

Then execute the remove() method on that element

●​ Removing a Child Node


For browsers that does not support the remove() method, you have to find the parent node to
remove an element:
Events in Javascript
In JavaScript, events are actions or occurrences that happen in the browser, which JavaScript can
respond to. Events can be triggered by user interactions (like clicks or key presses), by the browser
itself (like loading a page), or programmatically.

Types of Events in JavaScript


1. Mouse Events

●​ click – Fired when an element is clicked.​

●​ dblclick – Fired when an element is double-clicked.​

●​ mousedown – Fired when a mouse button is pressed down.​

●​ mouseup – Fired when a mouse button is released.​

●​ mousemove – Fired when the mouse moves over an element.​

●​ mouseenter / mouseover – Fired when the mouse enters an element.​

●​ mouseleave / mouseout – Fired when the mouse leaves an element.​

●​ contextmenu – Fired when the right mouse button is clicked.​

2. Keyboard Events

●​ keydown – Fired when a key is pressed.​

●​ keyup – Fired when a key is released.​

●​ keypress – (Deprecated) Similar to keydown, but only for printable characters.​

3. Form Events

●​ submit – Fired when a form is submitted.​


●​ change – Fired when an input, select, or textarea value changes.​

●​ input – Fired when a user types or changes input value.​

●​ focus – Fired when an element gains focus.​

●​ blur – Fired when an element loses focus.​

●​ reset – Fired when a form is reset.​

4. Window & Document Events

●​ load – Fired when a page or resource is loaded.​

●​ resize – Fired when the window is resized.​

●​ scroll – Fired when the user scrolls a page.​

●​ unload – Fired when the user leaves the page.​

5. Clipboard Events

●​ copy – Fired when content is copied.​

●​ cut – Fired when content is cut.​

●​ paste – Fired when content is pasted.​

6. Drag & Drop Events

●​ dragstart – Fired when an element starts being dragged.​

●​ drag – Fired while dragging.​

●​ dragenter – Fired when the dragged element enters a drop target.​


●​ dragover – Fired when an element is dragged over a valid drop target.​

●​ drop – Fired when an element is dropped.​

●​ dragend – Fired when the drag operation is complete.​

Handling Events in JavaScript


There are three main ways to handle events:

1. Inline Event Handlers

Inside html

<button onclick="alert('Button clicked!')">Click Me</button>

2. Using addEventListener() (Best Practice)

Inside javascript

document.getElementById("myButton").addEventListener("click",
function () {

alert("Button clicked!");

});

3. Using Event Properties

javascript

<script>

const button = document.getElementById("myButton");

button.onclick = function () {
alert("Button clicked!");

};

</script>

Event Object (event)


When an event occurs, JavaScript provides an event object containing information about the event.

javascript

document.addEventListener("click", function (event) {

console.log("Mouse clicked at:", event.clientX,


event.clientY);

});

Note : event.clientX and **event.clientY provides the coordinates relative to the


element taking into account margin, padding and border measures
​ Events:​
Events are actions or occurrences that happen in a program or application,
like a mouse click, a keyboard press, or a page load.
​ Event Handlers:​
These are the functions or methods that are designed to respond to
specific events.

Event Trigger:​
When an event occurs, the event handler is triggered, and the code within the
handler is executed
JavaScript Libraries
A JavaScript library is a collection of classes, methods, and pre-written
functions that developers can use in their web development projects.
Libraries make code reusable and simplify the development process. They
are also favored for their cross-browser compatibility, saving developers time
and effort. Some popular JavaScript libraries include:JQuery , React etc
Introduction to jQuery

●​ jQuery is a fast, small, and feature-rich JavaScript library.​

●​ It simplifies tasks like HTML document manipulation,


event handling, animation, and AJAX.​

●​ It works on all major browsers.​

Why Use jQuery?

●​ Easy to learn and write.​

●​ Reduces the amount of JavaScript code needed.​

●​ Cross-browser compatibility.​

●​ Provides built-in effects and animations.​

How to Include jQuery?

There are two ways to include jQuery in a webpage:

1.​CDN (Content Delivery Network) (Recommended)​


Add this line inside the <head> section:​

html​

<script
src="https://code.jquery.com/jquery-3.6.0.m
in.js"></script>

2.​Download and Include Manually​

○​ Download jQuery from https://jquery.com/​

○​ Add it to your project folder.​

Include it using:​

​ ​ html​
<script src="jquery-3.6.0.min.js"></script>

○​
Basic jQuery syntax:​

$(selector).action();

○​ $ → Defines jQuery.​

○​ selector → Selects HTML elements.​

○​ action() → Performs an operation.​

Example: Hide a Paragraph

html

<!DOCTYPE html>

<html>

<head>

<script
src="https://code.jquery.com/jquery-3.6.0.min.j
s"></script>

<script>
$(document).ready(function(){

$("#btn").click(function(){

$("p").hide();

});

});

</script>

</head>

<body>

<p>This is a paragraph.</p>

<button id="btn">Hide</button>

</body>

</html>

●​ When the button is clicked, the paragraph hides.​

Common jQuery Selectors

jQuery selectors are used to "find" (or select) HTML elements based on their
name, id, classes, types, attributes, values of attributes and much more.
selectors in jQuery start with the dollar sign and parentheses: $().
Selector Description

$("p") Selects all <p>


elements

$("#id") Selects an element


by id

$(".class") Selects elements by


class

$("div:first") Selects the first


<div>

Common jQuery Methods

Method Description

hide() Hides elements

show() Shows hidden


elements

toggle() Toggles between


hide and show

fadeIn() Fades in an element


fadeOut() Fades out an
element

The Document Ready Event


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

This is to prevent any jQuery code from running before the document is finished
loading (is ready).
jQuery Animations - The animate() Method
The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);

The required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take
the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the animation


completes.
The following example demonstrates a simple use of the animate() method; it
moves a <div> element to the right, until it has reached a left property of
250px:

Example

$("button").click(function(){

$("div").animate({left: '250px'});

});

What is AJAX?
●​ AJAX (Asynchronous JavaScript and XML) allows web pages to update without
reloading.​

●​ It sends and receives data from a server in the background.​

●​ Used in modern web applications like Google Search, Facebook, and Gmail.
●​ Eg: when we like a post in FB, only the like count get updated. The full fb page is not
refreshed.​

Why Use AJAX?

●​ Faster webpage interactions.​

●​ No full page reload needed.​

●​ Improves user experience.​

How AJAX Works?

1.​ A request is sent to the server (e.g., user clicks a button).​


2.​ The server processes the request.​

3.​ The server sends back data (e.g., JSON, XML, or HTML).​

4.​ The webpage updates without refreshing.​

AJAX Using jQuery

jQuery simplifies AJAX with the .ajax() method.

Example: Load data from a file

html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("#content").load("data.txt");
});
});
</script>
</head>
<body>
<button id="btn">Load Data</button>
<div id="content"></div>
</body>
</html>

●​ When the button is clicked, content from data.txt is loaded into the <div>.​
Common AJAX Methods in jQuery
Method Description

$.ajax() Sends an AJAX request.

$.get() Sends a simple GET request.

$.post() Sends data using POST.

load() Loads data from a server and


inserts it into an element.

Example: Fetch Data from a Server (GET Request)


js
$.get("data.txt", function(data){
$("#content").html(data);
});

●​ Fetches data.txt and displays it inside #content.​

What is JSON?

●​ JSON (JavaScript Object Notation) is a lightweight data format.​

●​ It is used for storing and exchanging data between a server and a web application.​

●​ JSON is easy to read and faster than XML.​

Why Use JSON?

●​ Simple and human-readable.​

●​ Supports key-value pairs (like a dictionary).​

●​ Lightweight (uses less data).​

●​ Works well with JavaScript, Python, PHP, etc.​

JSON Syntax
●​ Data is stored as key-value pairs inside {} (curly braces).​

●​ Uses arrays ([]) to store multiple values.​

●​ Keys are in double quotes ("").​

Example of JSON Data


json
CopyEdit
{
"name": "John",
"age": 25,
"city": "New York",
"skills": ["JavaScript", "Python", "Java"]
}

●​ name, age, city are keys.​

●​ "John", 25, "New York" are values.​

●​ skills is an array.​

How to Use JSON in JavaScript?

JSON is often used to send and receive data between a browser and a server.

Convert JSON to JavaScript Object


js
CopyEdit
let jsonData = '{"name": "John", "age": 25, "city": "New York"}';
let obj = JSON.parse(jsonData);
console.log(obj.name); // Output: John

●​ JSON.parse() converts a JSON string into a JavaScript object.

You might also like