JAVASCRIPT-MODULE 4 Full
JAVASCRIPT-MODULE 4 Full
What is JavaScript?
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
</script>
</body></html>
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
1.Using innerHTML
To access an HTML element, you can use the document.getElementById(id) method.
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.
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
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
var n = 5;
console.log(n);
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;
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;
console.log(n)
Output
100
Data Types
Primitive Datatypes
let n = 42;
let pi = 3.14;
4. Undefined: A variable that has been declared but not assigned a value.
let notAssigned;
console.log(notAssigned);
Output
undefined
6. Symbol: Represents unique and immutable values, often used as object keys.
Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex
entities.
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
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.
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
console.log(sum, diff, p, q );
Output
8884
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
Comparison operators compare two values and return a boolean (true or false). They
are useful for making decisions in conditional statements.
Output
true
false
Comparison operators are mainly used to perform the logical operations that
determine the equality or difference between the values.
false
true
The ternary operator is a shorthand for conditional statements. It takes three operands.
console.log(status);
Output
Adult
let x = 5;
console.log(++x); // Pre-increment
Output
console.log(s);
Output
Hello World
● + concatenates strings.
● += appends to an existing string.
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 ) {
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{
Example:
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:
The conditional operator, also referred to as the ternary operator (?:), is a shortcut
for expressing conditional statements in JavaScript.
Syntax:
Example:Output
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:
// 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:
DOM 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
You can use the following node properties to navigate between nodes with
JavaScript:
● parentNode
● childNodes[nodenumber]
● firstChild
● lastChild
● nextSibling
● previousSibling
myTitle = document.getElementById("demo").firstChild.nodeValue;
The easiest way to modify the content of an HTML element is by using the
innerHTML property.
To do so, you have to find the elements first. There are several ways to do this:
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.
const x = document.querySelectorAll("p.intro");
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
2. Keyboard Events
3. Form Events
5. Clipboard Events
Inside html
Inside javascript
document.getElementById("myButton").addEventListener("click",
function () {
alert("Button clicked!");
});
javascript
<script>
button.onclick = function () {
alert("Button clicked!");
};
</script>
javascript
});
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
● Cross-browser compatibility.
Include it using:
html
<script src="jquery-3.6.0.min.js"></script>
○
Basic jQuery syntax:
$(selector).action();
○ $ → Defines jQuery.
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>
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
Method Description
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 optional speed parameter specifies the duration of the effect. It can take
the following values: "slow", "fast", or milliseconds.
Example
$("button").click(function(){
$("div").animate({left: '250px'});
});
What is AJAX?
● AJAX (Asynchronous JavaScript and XML) allows web pages to update without
reloading.
● 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.
3. The server sends back data (e.g., JSON, XML, or HTML).
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
What is JSON?
● It is used for storing and exchanging data between a server and a web application.
JSON Syntax
● Data is stored as key-value pairs inside {} (curly braces).
● skills is an array.
JSON is often used to send and receive data between a browser and a server.