0% found this document useful (0 votes)
20 views

Front End Web Technologies-Javascript

java script study

Uploaded by

purswanijiten11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Front End Web Technologies-Javascript

java script study

Uploaded by

purswanijiten11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Javascript

Prof. Prerna Solanke


Introduction to Javascript
● JavaScript is a scripting language of the web.
● It is designed to interact with elements of web pages.
● It allows you to add interactivity to a web page.
● It is case sensitive.
● Typically, JavaScript is used with HTML and CSS to enhance a
web page’s functionality, such as validating forms, creating
interactive maps, and displaying animated charts.
Client-side vs. Server-side JavaScript
● When JavaScript is used on a web page, it is executed in web
browsers. In this case, JavaScript works as a client-side language.
● JavaScript can run on both web browsers and servers.
● A popular JavaScript server-side environment is Node.js.
● Unlike client-side JavaScript, server-side JavaScript executes on
the server that allows you to access databases, file systems, etc.
Node.js is an open-source and cross-platform runtime
environment that allows to use JavaScript to develop server-side
applications.
What can JavaScript do?
What makes JavaScript unique?
JavaScript Framework and Libraries
Internal and External JavaScript
There are 2 ways to use the javascript in the HTML file:
● Internal JavaScript: JavaScript can be added directly to the HTML file
by writing the code inside the <script> tag . We can place the <script>
tag either inside <head> or the <body> tag according to the need.
Syntax: <script> // JS code goes here </script>

● External JavaScript: The other way is to write JavaScript code in


another file having .js extension and then link the file inside the
<head> or <body> tag of the HTML file in which we want to add this
code.
Syntax: <script src="myscript.js"> </script>
JavaScript Code Editors
To edit JavaScript source code, you need a plain text editor such as
Notepad. However, to simplify and speed up typing of JavaScript code,
you need a JavaScript code editor.
The popular JavaScript code editors:
● Visual Studio Code
● Atom
● Notepad++
● Vim
● GNU Emacs
Internal JavaScript file
<!DOCTYPE html>
<html lang="en"> In the <script> element,
<head> we use the alert() function
<meta charset="UTF-8"> to display the Hello
<title>JavaScript Hello World</title>
World! message.
</head>
<body>
<script>
alert('Hello World!');
</script>
</body>
</html>
External JavaScript file
First create a file with .js extension.
For example:
If you launch the html file of
app.js file: Hello world in the web
browser, you will see an
alert('Hello, World!');
alert that displays the Hello
Use this html file with src attribute: World! message.
<script src="app.js"></script>
External JavaScript file
First create a file with .js extension.
For example:
app.js file: alert('Hello, World!');
app1.js file: alert('This is Javascript example');
Use this html file with src attribute:
<script src="app.js"></script>
<script src="app1.js"></script>
In this example, JavaScript engine will interpret aap.js and app1.js files in sequence.
Example 1:

<!DOCTYPE html>
<body>
<script language ="javascript" type ="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Example 2:

<!DOCTYPE html>
<html lang="en">
<body>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
<input type ="button" onclick ="sayHello()" value ="Say Hello"/>
</body> </html>
Example 3:
Example 4:
DOM Model
● The Document Object Method (DOM) is a programming interface
for web documents. It represents the page so that programs can
change the document structure, style, and content.
● When a web page is loaded in the browser, another
representation of that document is created, called as DOM of that
page.
● The DOM represents HTML elements as nodes or objects; that way,
programming languages can interact with the page.
DOM Model
DOM Model
Why JS need DOM Model ?
● Javascript easily interpret this hierarchical DOM format.
● It can not understand HTML format but it easily understand DOM
format of the HTML document where each HTML element is
represented as object or node.
● Thus JS uses nodes to understand document and divide it into
three categories: Element node, Attribute node and Text node.
DOM
With the DOM model, JavaScript gets all the power it needs to create
dynamic HTML:

● JavaScript can change all the HTML elements and attributes in the
page.
● It can remove existing HTML elements and attributes.
● It can add new HTML elements and attributes.
● It can create new HTML events in the page.
● It can change all the CSS styles in the page
DOM Programming Interface
● The HTML DOM can be accessed with JavaScript (and with
other programming languages).
● In the DOM, all HTML elements are defined as objects.
● The programming interface is the properties and methods of
each object.
○ A property is a value that you can get or set (like changing the
content of an HTML element).
○ A method is an action you can do (like add or deleting an HTML
element).
How to Access the DOM
● Accessing elements in the DOM means finding specific parts of a
website and changing or manipulating them.
● JavaScript provides different methods to access the elements in the
DOM, such as getElementById, getElementsByClassName,
querySelector, and querySelectorAll. These methods allow you to
find an element based on its id, tagname, or classname and select it
for manipulation.
● For example, you can access a button on a webpage and change its
text or color when a user clicks on it. Or, you can access an image on
a webpage and change it to a different image when a user hovers
over it.
getElementById() method
The getElementById() method returns the elements of specified ID which
is passed to the function.
Every HTML element can be assigned a unique ID. If two or more elements
have the same ID, then the getElementByID() method returns the first
element.

Syntax:
document.getElementByID(id);

Where, id is the element id which is to be returned. It is case-sensitive. An


element object is returned.
getElementById() method
getElementById() method

The console.log() method in


JavaScript logs messages or
data to the console,
getElementById() method
getElementById() method
innerHTML property
DOM innerHTML property returns the text content of the element,
including all spacing and inner HTML tags.

Syntax:
Object.innerHTML
(It is used to set the innerHTML property)

Object.innerHTML = value
(value: It represents the text content of the HTML element)
innerHTML property
innerHTML property
<!DOCTYPE html>
<html>
<body>
<h2>The innerHTML Property</h2>
<div id="myDIV">This is a div element.
<p id="myP">This is a p element.</p>
</div>
<script>
var x= document.getElementById("myDIV").innerHTML;
console.log(x);
</script>
</body>
</html>
innerHTML property
innerHTML property
<!DOCTYPE html>
<html>
<body>
<h2>The innerHTML Property</h2>
<p id="myP">This is a p element.</p>
<div id="myDIV">This is a div element.</div>
<script>
let text = "Hello World !!";
document.getElementById("myP").innerHTML=text;
document.getElementById("myDIV").innerHTML = text;
</script>
</body>
</html>
innerHTML property
<!DOCTYPE html>
<html>
<body>
<h2>The innerHTML Property</h2>
<p id="myP">This is a p element.</p>
<div id="myDIV">This is a div element.</div>
<script>
var text = "Hello World !!";
document.getElementById("myP").innerHTML;
var x= document.getElementById("myDIV").innerHTML=text;
console.log(x);
</script>
</body>
</html>
Difference Between innerHTML, innerText and textContent
The innerHTML property returns:
The text content of the element, including all spacing and inner
HTML tags.
The innerText property returns:
Just the text content of the element and all its children, without CSS
hidden text spacing and tags, except <script> and <style> elements.
The textContent property returns:
The text content of the element and all descendants, with spacing
and CSS hidden text, but without tags.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_textcontent_innerhtml_innertext
getElementsByClassName() method
● The getElementsByClassName() method in Javascript returns an object
containing all the elements with the specified class names in the
document as objects.
● Each element in the returned object can be accessed by its index. The
index value will start with 0.
● This method can be called upon by any individual element to search for its
descendant elements with the specified class names.
● Syntax:
document.getElementsByClassName(classname);
getElementsByClassName() method
<!DOCTYPE html>
<html>
<body>
<h3>The getElementsByClassName()
Method</h3>

<div class="example">Element1</div>
<div class="example">Element2</div>

<script>
var x = document.getElementsByClassName("example");
</script>
</body>
</html>
getElementsByClassName() method
<!DOCTYPE html>
<html>
<body>
<h3>The getElementsByClassName()
Method</h3>
<div class="example">Element1</div>
<div class="example">Element2</div>
<script>
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
x[1].innerHTML = "Welcome!";
</script>
</body>
</html>
getElementsByClassName() method
<!DOCTYPE html>
<html>
<body>
<h3>The getElementsByClassName() Method</h3>

<div class="example">Element1</div>
<div class="example">Element2</div>

<script>
var x = document.getElementsByClassName("example");
x[0].style.backgroundColor = "red";
x[1].style.backgroundColor = "green";
</script>
</body>
</html>
getElementsByClassName() method
<body> <script>
<p>Change the background color of all var x =
elements with class="example":</p> document.getElementsByClassName("
<div class="example"> example");
A div with class="example" for (let i = 0; i < x.length; i++) {
</div> x[i].style.backgroundColor = "green";
<br> }
<div class="example"> </script>
A div with class="example" </body>
</div>
<p>A <span
class="example">span</span> element
with class="example".</p>
Variable and data types in JS
● Variables are Containers for Storing Data.
● Variables name always starts with alphabet or underscore and not
with numbers.
● Note: JS is case sensitive. For example, Demo , deMo and demo
are 3 different variable.
● JavaScript Variables can be declared in 4 ways:
○ Automatically
○ Using var
○ Using let
○ Using const
Variable and data types in JS
1. Automatic declaration of variable
<script>
In this first example, x, y, and z
x = 5; are undeclared variables. They
y = 6; are automatically declared
when first used
z = x + y;
document.write("The value of z is: " + z);
</script>
2. Using var
<script>

var num = 5; // holding a number


JavaScript is a dynamic type
language, means you don't
var Name = "Prerna"; // holding a string need to specify type of the
var flag = true; // boolean value variable. It just need to
document.write(Name);
specify the data type. It can
hold any type of values such
</script> as numbers, strings etc.
3. Using let
<script>
let x = 5;
let y = 6;
let z = x + y;
document.write("The value of z is: " + z);
</script>
3. Using let
Variables defined with let can not be redeclared.
For example:
With let you can not do this:
let x = "Prerna";
With var you can:
let x = 0;
var x = " Prerna";
var x = 0;
3. Using let
Variables defined with let have Block scope i.e., Variables declared
inside a { } block cannot be accessed from outside the block
For example:
{
With var you can access it
let x = 2;
outside block { } :
} {
// x can NOT be used here var x = 2;
}
// x CAN be used here
Re-declaring variable using var and let:

Redeclaring a variable using Redeclaring a variable using


the var keyword: the let keyword:
var x = 10; let x = 10;
// Here x is 10 // Here x is 10
{ {
var x = 2; let x = 2;
// Here x is 2 // Here x is 2
} }
// Here x is 2 // Here x is 10
4. Using const
● Variables defined with const cannot be Redeclared
● Variables defined with const cannot be Reassigned
● Variables defined with const have Block Scope

const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
4. Using const
You can change the elements of a constant array But you can NOT
reassign the array.

For example:
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
4. Using const
Block scope: Declaring a variable with const is similar to let when it
comes to Block Scope.
For example:
const x = 10; const x = 2; // Allowed
// Here x is 10 {
{ const x = 3; // Allowed
}
const x = 2;
// Here x is 2 {
} const x = 4; // Allowed
// Here x is 10 }
Built in objects in JS
Built-in objects are used for simple data processing in the
JavaScript. It is a collection of properties and methods.
Built in objects in JS - Math object
Math object is a built-in static object. It is used for performing
complex math operations.

Methods of Math object:


● max(a,b) - Returns largest of a and b
● min(a,b) - Returns least of a and b
● round(a) - Returns nearest integer
● ceil(a) - Rounds up. Returns the smallest integer greater than or
equal to a
Built in objects in JS - Math object
● floor(a) - Rounds down. Returns the largest integer smaller than or
equal to a.
● pow(a,b) - Returns value of a to the power b
● abs(a) - Returns absolute value of a
● random() - Returns a pseudo random number between 0 and 1
● sqrt(a) - Returns square root of a
● sin(a) - Returns sin of a (a is in radians)
● cos(a) - Returns cos of a (a is in radians)
Built in objects in JS- Math object
The syntax for any Math property is : Math.property.
Built in objects in JS - Math object example
<!DOCTYPE html>
<body>
<h3>Math Object</h3>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>
</body>
</html>
Built in objects in JS - Math object example
<!DOCTYPE html>
<body>
<h3>JavaScript Math.pow()</h3>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.pow(8,3);
</script>
</body>
</html>
Built in objects in JS- Date Object
● Date object manipulates date and time.

● Date() constructor takes no arguments.

● Date object allows you to get and set the year, month, day, hour,

minute, second and millisecond fields.


Built in objects in JS- Date Object
Methods of Date object:
● Date() - Returns today's date and time
● getDate() - Returns the day of the month for the specified date
● getDay() - Returns the day of the week for the specified date
● getFullYear() - Returns the year of the specified date
● getHours() - Returns the hour in the specified date according to
local time.
● getMilliseconds() - Returns the milliseconds in the specified date
according to local time.
Built in objects in JS- Date Object
<!DOCTYPE html>
<body>
<h1>JavaScript Dates</h1>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Built in objects in JS- Date Object
<!DOCTYPE html>
<body>
<h3>JavaScript Dates</h3>
<p id="demo"></p>
<script>
const d = new Date("2025-01-01");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Built in objects in JS- String Object
● String object used to perform operations on the stored text, such
as finding the length of the string, searching for occurrence of
certain characters within string, extracting a substring etc.
● A String is created by using literals. A string literal is either
enclosed within single quotes(‘ ‘) or double quotes(“ “).

For example, var string1= “ Prerna “ ;


Built in objects in JS- String Object
charAt() - Returns the character at a specified index (position)
charCodeAt()- Returns the Unicode of the character at a specified
index
concat()- Returns two or more joined strings
indexOf() - Returns the index (position) of the first occurrence of a
value in a string
Length - Returns the length of a string
Built in objects in JS- String Object
repeat() - Returns a new string with a number of copies of a string
replace() - Searches a string for a pattern, and returns a string where
the first match is replaced
replaceAll() - Searches a string for a pattern and returns a new string
where all matches are replaced
search()- Searches a string for a value, or regular expression, and
returns the index (position) of the match
Built in objects in JS- String Object
toLowerCase() - Returns a string converted to lowercase letters

toUpperCase() - Returns a string converted to uppercase letters

trim() - Returns a string with removed whitespaces

match() - Searches a string for a value, or a regular expression, and


returns the matches
slice() - Extracts a part of a string and returns a new string
Built in objects in JS- String Object
<!DOCTYPE html>
<body>
<h2>The charAt() Method</h2>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
let letter = text.charAt(6);
document.getElementById("demo").innerHTML = letter;
</script>
</body>
</html>
Built in objects in JS- String Object
<!DOCTYPE html>
<body>
<h2>The repeat() Method</h2>
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.repeat(3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Built in objects in JS- Array Object
● Multiple values are stored in a single variable using the Array
object.
● In JavaScript, an array can hold different types of data types in
a single slot, which implies that an array can have a string, a
number or an object in a single slot.
Built in objects in JS- Array Object
<script>
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
document.write(cars);
</script>
Built in objects in JS- Array Object
<h2>The length Property</h2>
<p>The length property returns the length of an array:</p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
document.write(size);
</script>
Functions in JS
● A function is a JavaScript procedure—a set of statements that
performs a task or calculates a value.
● A JavaScript function is a block of code designed to perform a
particular task.
● JS function is executed when “something” invokes it (calls it).
Syntax :
function name(parameter1, parameter2, parameter3)
{
code to be executed
}
Function example
<head><title>Functions in JS</title></head>
<script type="text/javascript">
function addNumber(a , b)
{
var total = a+b;
return total;
}
var output = addNumber(4,2); // function call
document.write("<h1>The total is : "+output+"</h1>");
</script>
Function example
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type ="button" onclick ="sayHello()" value ="Say Hello" />
</form>
Form validation in JS
● Web forms are used to collect user's information such as name,
email address, location, age, and so on.
● But sometimes users do not enter the expected details. So it is
crucial to validate the form data before sending it to the
server-side. For form validation, client-side JavaScript can help us.
● Form validation checks the accuracy of the user’s information
before submitting the form.
Form validation in JS
Sign up on a website where certain requirements are there like:
● Ensuring your password is between 8 to 30 characters or making sure
your password is mixed between letters, numbers, and asterisks.
● Or ensure you include the @ for the email input field by popping
messages like "Please enter a valid email address".
● "This field is required" (You can't leave this field blank)
This is called Validation. When you enter your details on a form website,
the browser and/or web server will check to see that the data is in the
correct format.
Form validation example in JS
Form validation example in JS
<head>
Form validation <script>
example in JS function validate() {
var username = document.getElementById('uname');
var password = document.getElementById('pass');
if (username.value == "" ||password.value == "" )
{
alert("No blank value allowed");
return false;
}
else {
true;
}}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form action="message.html" onsubmit="return validate()">
Username: <input type="text" placeholder="username" id="uname"><br>
Password: <input type="password" placeholder="password" id="pass"><br>
<input type="submit" value="Submit">
</form>
</body>

message.html
Event Handling in JS
Event Handling in JavaScript is a software routine that processes
actions that happen when a user interacts with the page, such as
mouse movements and keystrokes.
Event handlers can be assigned directly using the equal (=) operator
because they are attributes of HTML/DOM elements as well.
Syntax:
name_of_EventHandler = "The javaScript code / function which is
required to be executed"
Event Handling in JS

When a user clicks a specific mouse button or type a specific keyword


into the browser, that action activates the corresponding event handler
for that HTML element.
The browser then shows the end users the effects of the actions that
were carried out on the webpage by the JavaScript code that was
executed by the event handler.
Event Handling in JS
Example of event handler attributes:
<script>
function myAlert() {
alert('The button is clicked!');
}
</script>
<input type="button" value="Submit" onclick="myAlert()">

The names of event handlers typically start with on; for example,
onclick is the name of the event handler for the click event.
Event Handling in JS
Common HTML Event in JS
Common HTML Event in JS
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmouseover

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove
_leave_out

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onchange

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onload

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeydown
Exception handling in JS
exception handling is a process or method used for handling the
abnormal statements in the code and executing them. It also enables
to handle the flow control of the code/program.
The try statement defines a code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the


result.

The throw statement defines a custom error.

You might also like