KEMBAR78
Javascript | PDF | Java Script | Html
0% found this document useful (0 votes)
21 views20 pages

Javascript

JavaScript is a lightweight, interpreted programming language designed for network-centric applications and is integrated with HTML. It allows for dynamic manipulation of web pages, client-side validation, and supports server applications through Node.js. Key concepts include the Document Object Model (DOM), variable declaration, data types, and functions, which are essential for web development.

Uploaded by

itstd.6375
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)
21 views20 pages

Javascript

JavaScript is a lightweight, interpreted programming language designed for network-centric applications and is integrated with HTML. It allows for dynamic manipulation of web pages, client-side validation, and supports server applications through Node.js. Key concepts include the Document Object Model (DOM), variable declaration, data types, and functions, which are essential for web development.

Uploaded by

itstd.6375
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/ 20

JavaScript Part1

JavaScript
● JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications. It is complementary to and integrated with Java. JavaScript is
very easy to implement because it is integrated with HTML. It is open and cross-platform.
● When a web page is loaded, i.e., after HTML and CSS have been downloaded, the
JavaScript engine in the web browser executes the JavaScript code. The JavaScript code
then modifies the HTML and CSS to update the user interface dynamically.
● The JavaScript engine is a component of web browsers responsible for interpreting and
executing JavaScript code. It includes a parser to analyze the code, a compiler to convert it
into machine code, and an interpreter to run the compiled code.
● Initially, JavaScript engines were implemented as interpreters. However, modern JavaScript
engines are commonly implemented as just-in-time compilers that compile JavaScript code to
bytecode for improved performance.
JavaScript Applications
● Client side validation - This is really important to verify any user input before submitting it to the
server and Javascript plays an important role in validating those inputs at front-end itself.
● Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in
adding and deleting any HTML tag very easily using javascript and modify your HTML to change its
look and feel based on different devices and requirements.
● User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
● Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data
while you are doing some other processing. This really gives an amazing experience to your website
visitors.
● Presentations - JavaScript also provides the facility of creating presentations which gives website
look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide
presentations.
● Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and
scalable network applications. This is an event based library which helps in developing very
sophisticated server applications including Web Servers
JS Syntax
Internal JS scripts:
● 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 <body> or
<head>, 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>

External JS scripts:
● External scripts are practical when the same code is used in many different web pages. JavaScript files have
the file extension .js. To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
<script src="myScript.js"></script>
● You can place an external script reference in <head> or <body> as you like. The script will behave
as if it was located exactly where the <script> tag is located.
JS HTML DOM
● The Document Object Model (DOM) is an essential concept in web development. It
represents the structure of a web page as a tree of objects. JavaScript can interact with
the DOM to modify content, structure, and styles dynamically.
● When a web page is loaded, the browser creates a Document Object Model of the page.
● The HTML DOM is a standard object model and programming interface for HTML. It defines:
○ The HTML elements as objects
○ The properties of all HTML elements
○ The methods to access all HTML elements
○ The events for all HTML elements
● In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
● If you want to access any element in an HTML page, you always start with accessing the
document object.
Finding HTML Elements
Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Property Description

element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML element


Finding & Changing HTML Elements Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p class="styled">My First Paragraph</p>

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

<script>
document.getElementsByTagName("h1")[0].innerHTML = "My New Heading";
document.getElementsByClassName("styled")[0].style.color = "red";
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Adding & Deleting Elements
Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

Adding Events Handlers


Method Description

document.getElementById(id).onclick = Adding event handler code to an onclick


function(){code} event
Explain Code
const newDiv = document.createElement("div");
Purpose: Creates a new HTML element specified by the element argument (a string representing the tag name).
Usage: This method returns a new element but does not attach it to the document until you use methods like appendChild.

const parent = document.getElementById("parent");


const child = document.getElementById("child");
parent.removeChild(child);
Purpose: Removes a specified child element from its parent node.
Usage: You must call this method on the parent node of the element you want to remove.

const parent = document.getElementById("parent");


const newDiv = document.createElement("div");
parent.appendChild(newDiv);
Purpose: Adds a new child node (element) to a specified parent node.
Usage: The element is added as the last child of the parent node.

const parent = document.getElementById("parent");


const newDiv = document.createElement("div");
const oldDiv = document.getElementById("oldDiv");
parent.replaceChild(newDiv, oldDiv);
Purpose: Replaces an existing child node (old) with a new node (new) within a specified parent node.
Usage: You need to call this method on the parent node of the old element.
Finding & Changing HTML Elements Example

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p class="styled">My First Paragraph</p>
<p id="demo"></p>
<button id="addElement">ADD</button>

<script>
document.getElementsByTagName("h1")[0].innerHTML = "My New Heading";
document.getElementsByClassName("styled")[0].style.color = "red";
document.getElementById("demo").innerHTML = 5 + 6;
document.getElementById("addElement").onclick = function(){
var newdiv = document.createElement("div")
newdiv.innerHTML = "Hello!"
document.getElementById("demo").appendChild(newdiv)
}
</script>
</body>
</html>
Explain pre Code
<p id="demo"></p>
This is an empty paragraph element with an ID of "demo". This ID allows it to be targeted by JavaScript
for dynamic content updates.

<button id="addElement">ADD</button>
This button, when clicked, will trigger an action defined in the JavaScript code. It has an ID of
"addElement".

document.getElementsByTagName("h1")[0].innerHTML = "My New Heading";


This changes the content of the first <h1> element to "My New Heading".

document.getElementsByClassName("styled")[0].style.color = "red";
This changes the text color of the first paragraph with the class "styled" to red.

document.getElementById("demo").innerHTML = 5 + 6;
This sets the inner HTML of the element with the ID "demo" to 11, which is the result of 5 + 6.
Explain pre Code (con’t)
document.getElementById("addElement").onclick = function() { ... };
This sets up an event handler that executes the function when the button with ID
"addElement" is clicked.

var newdiv = document.createElement("div");


This creates a new <div> element and assigns it to the variable newdiv.

newdiv.innerHTML = "Hello!";
This sets the content of the newly created <div> to "Hello!".

document.getElementById("demo").appendChild(newdiv);
This appends the new <div> (containing "Hello!") as a child to the paragraph with the ID
"demo". This means that when the button is clicked, "Hello!" will be added below the
previous content in that paragraph.
JS Variables Declaration
● JavaScript Variables can be declared in 4 ways:
○ Automatically: x = 5;
○ Using var: var x = 5;
○ Using let: let x = 5;
○ Using const: const x = 5;
● The let and const keywords were added to JavaScript in 2015.
● The var keyword should only be used in code written for older browsers.
● The Assignment Operator (=) assigns a value to a variable:

JavaScript Identifiers
● All JavaScript variables must be identified with unique names.
● These unique names are called identifiers.
● Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
● The general rules for constructing names for variables (unique identifiers) are:
○ Names can contain letters, digits, underscores, and dollar signs.
○ Names must begin with a letter.
○ Names can also begin with $ and _ (but we will not use it in this tutorial.
○ Names are case sensitive (y and Y are different variables).
○ Reserved words (like JavaScript keywords) cannot be used as names.
● JavaScript identifiers are case-sensitive.
Arithmetic Operators

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement
Assignment Operators

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

**= x **= y x = x ** y
Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator. Example: condition ? exprIfTrue : exprIfFalse


JS Data Types
• String: are written with quotes. You can use single or double quotes. let carName1 = "Volvo XC60";
Number: can be written with, or without decimals. let x1 = 34.50; let x2 = 34;
○ Extra large or extra small numbers can be written with scientific (exponential) notation:
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
● Bigint: is a new data type that can be used to store integer values that are too big to be represented
by a normal JavaScript Number. let x = BigInt("123456789012345678901234567890");
● Boolean: can only have two values: true or false.
● Undefined: a variable without a value, has the value undefined. The type is also undefined.
● Array: is written with square brackets. Array items are separated by commas and their indexes are
zero-based, which means the first item is [0], second is [1], and so on. const cars = ["Saab", "Volvo",
"BMW"];
● Object: is written with curly braces {}. its properties are written as name:value pairs, separated by
commas. const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
● You can use the JavaScript typeof operator to find the type of a JavaScript variable. typeof ""
JS Functions
● A JavaScript function is a block of code designed to perform a particular task. It is executed when
"something" invokes it (calls it).
● A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
○ Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
○ The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
○ The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
● Functions often compute a return value. The return value is "returned" back to the "caller".
● When JavaScript reaches a return statement, the function will stop executing. If the function was
invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
JS Functions
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

function myFunction(a, b) {
return a * b;
}
• This line defines a function named myFunction that takes two parameters: a and b.

• Inside the function, it calculates the product of a and b using the multiplication operator (*) and returns
that value. The return statement sends the result back to the caller of the function.
Explain pre Code
let x = myFunction(4, 3);
This line calls the myFunction with the arguments 4 and 3.

When the function is called, the values 4 and 3 are passed to the parameters a and b,
respectively.

Return Value:
Inside myFunction, the expression a * b evaluates to 4 * 3, which equals 12.
The return statement then sends this value (12) back to where the function was called.

Assigning the Result:


The result of the function call (which is 12) is assigned to the variable x.
After this line executes, x will hold the value 12.

You might also like