SlideShare a Scribd company logo
1 of 104
WEB DEVELOPMENT
Javascript
JAVASCRIPT
•In September 1995, Brendan Eich, a programmer at Netscape
developed a programming language in just 10 days.
•This language was initially called Mocha, then LiveScript.
•In December 1995 Netscape and Sun(the organisation that owned
Java) had a license agreement regarding Javascript(then LiveScript)
hence it was renamed to Javascript and specifically "Java" script
because Java was the most popular language at that time and this
would help the marketing of Javascript as well.
History
ECMA International
European Computer Manufacturers Association (ECMA) is a nonprofit standards organization for information and communication systems. It acquired its current name in 1994,
when the European Computer Manufacturers Association (ECMA) changed its name to reflect the organization's global reach and activities. Offical name of java scripy
JAVASCRIPT
Applications of JavaScript
Excellent user interactivity: Javascript, it allows users to interact
with the webpage allowing us to build amazing websites and web
apps.
Web and Mobile app creation: Javascript based frameworks like
React, Angular, Vue allow us to build robust web applications.
Server-side development: We can also use Javascript to develop the
back end infrastructure of a web application by using
Node.js.Example: Netflix,
Game development: Javascript can also be used to develop browser
based games some of them are HexGL, CrossCode, etc.
Art: We can also make digital art on the HTML5 canvas by using
javascript based libraries.Example.js library
JAVASCRIPT
Applications of JavaScript
Client-side use of JavaScript
Javascript is mostly used for client-side scripting. (Code is run on the client's
browser)
It can be used to modify the web page’s user interface (the browser and its
DOM) and make pages interactive.
It deals with client-side processing like cookies, sessions.
It deals with the storage of the web browser i.e. local and session storage.
For example:
If the user selects a dark theme for a website once, the website is always in
dark theme whenever the user re-visits the page, this is because the user's
preference is stored in local storage by Javascript.
JAVASCRIPT
server side use of JavaScript
Javascript can also be used to for server side development. This is
possible because of Node.js.
Node.js is an application runtime environment that allows us to use
JavaScript for building server-side applications.
We can do things like database queries, network requests,
files on the server, running web servers, interacting with other
servers, handling data sent to the server, etc.
Server side scripting is responsible for showing dynamic content on
the webpage.
JAVASCRIPT
How to Insert JavaScript into an HTML Page
You can insert a JavaScript program into an HTML document in two
ways.
•Internal JavaScript
•External JavaScript
Both methods make use of the <script> tag
JAVASCRIPT
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="/javascript.js"></script>
</head>
<body>
<script>
console.log("Hello World!")
</script>
</body>
</html>
3 Ways of Printing
Using console.log()
The console.log() is a function used to log messages on the web console
Using document.write()
document.write() is another function you can use to print Hello World in
JavaScript.
Using alert()
The last function we will use to print Hello World in JavaScript is alert.
This function displays a pop-up box over the current window with the specified
message
.Using cofirm() creates a popup that contains two buttons ok and cancel.Where
on clicking ok button contains boolean true value and cancel contains Boolean
false value
Using prompt()// creates a popup that is used to take input from the user
Using async and defer
async and defer are <script> tag attributes that can be used to increase website
loading times.
With async, the file gets downloaded asynchronously and then executed as soon
as it’s downloaded.
With defer, the file gets downloaded asynchronously but executed only when the
document parsing is completed.
<script async src="script.js"></script>
Declaring Variables
Declaring variables
Declaring a Variable
One must create a variable before using it. In programming terms,
we call this declaring a variable. In Javascript, we can declare a
variable using either
let,
var, or
const keywords.
To declare a variable without using any keyword, we have to just
write the variable name and must assign a value to that variable. On
doing this, the variable becomes a global variable
However, it is not recommended to declare a variable without using var as it may alter the
of an already existing global variable
variables
Rules/Identifiers While Declaring a JavaScript Variable
To declare a JavaScript variable, one must know the rules to follow,
Rules are as follows:
•Variables are case-sensitive in JavaScript.
•We can use letters, digits, and symbols like a dollar sign ($)
and underscore
_ in a variable name.
•We cannot start a variable name with a digit (0-9).
•We cannot use any of the reserved keywords (function, return, type
of, break, etc.) of JavaScript as a variable name.
Var and let
The Difference Between 'var' and 'let’
1. The main difference between var and let is that the scope of the variable
is defined by let is limited to the block in which it is declared, whereas the
variable declared using var has a global scope, i.e., can be used throughout
the code
2. We cannot declare the same variable multiple times if one of them is
using let, whereas we can declare the same variable any number of times
using var.
let myName = "my name";
let myName = "not my name";
console.log(myName); //output => SyntaxError: redeclaration of let name
1. JavaScript Reserved Words
break case catch class
const continue debugger default
delete do else export
extends finally for function
if import in instanceof
new return super switch
this throw try typeof
var void while with
Data Types
What are Data Types in JavaScript?
There are mainly two types of data types in JavaScript:
1.Primitive data types.
2.Non-primitive data types.
Primitive Data Types in JavaScript
Primitive data types in javascript refer to those data types that are defined
the most basic level of the language.
There are 7 primitive data types in JavaScript:
1.Numbers
2.BigInt
3.String
4.Boolean
5.Undefined
6.Null
7.Symbol
Largest safe Integer: It represents
the largest integer value that can be
represented by javascript without
any overflow.
Representation: Number.MAX_SAFE_I
NTEGER
Value: 253 - 1 or
9007199254740991
Data types
Boolean Type
It can be declared by using the bool keyword
followed by the variable name. It can be
assigned only two values, true or false.
Syntax:
bool flag = false;
Primitive datatype
Symbol Data type
One of the reasons of adding the data type was to enable private
properties in JavaScript.
Symbols are often used to add unique property keys to an object that
won't collide with keys any other code might add to the object, and which
are hidden from any mechanisms other code will typically use to access
the object
Primitive datatype
String properties:
1. Indexing
2. Immutability:
let name = ‘abcd’;
name.toLowerCase(); // INVALID
OPERATION
solution: let newName =
name.toLowerCase();
console.log(newName);
3. Concatenation: var str3 = str1 + str2;
4. str.charAt(index);
5. By using the backslash character
We can also break the string into multiple lines using
backslashes ().
Primitive datatype
Method Description
charAt() Finds the character present at a particular index in the string.
concat() Concatenates the string arguments.
indexOf() returns the index of the first occurrence of the passed value.
lastIndexOf() returns the index of the last occurrence of the passed value.
toLowerCase() converts all the characters of the string into lowercase letters.
toUpperCase() converts all the characters of the string into uppercase letters.
split() divides the given string into an ordered list of substrings.
trim() removes additional spaces around the string.
toString() returns a string object as a string.
substring()
extracts the characters between two indices of a string and returns a
substring.
slice()
.length
extracts a section of a string and returns it as a new string, without
modifying the original string.
What are Data Types in JavaScript?
There are mainly two types of data types in JavaScript:
1.Primitive data types.
2.Non-primitive data types.
Non-primitive Data Types in JavaScript
Non-primitive data types are those data types that aren't defined at a basic
but are complex data types formed upon operations with primitive data types.
There are mainly 3 types of non-primitive (or complex) data types in JavaScript:
1.Object
2.Array
3.RegExp
Non-Primitive datatype
Declaration: Object in javascript is a collection of data that is kept in a
key-value pair manner.
Objects in javascript can be created by two methods:
1. Literal method:
let obj = {
key: "value"
}
2. By constructor method
let obj=new Object();
obj.name='javascript'
console.log(obj);
obj.course="hi";
console.log(obj);
<script>
let phone=Symbol("ph");
let phone2=Symbol("ph");
let students={
rollno:"1",
name:"abc",
age:" 20",
students[phone]=1234;
};
students[phone2]=3456;
students.gender="male";
console.log(students)
JSON.stringify(students)
</script>
<script>
let students={
rollno:"1",
name:"abc",
age:" 20",
};
students.gender="male";
console.log(students)
</script>
Non-Primitive datatype
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<script>
function Students(rollno,name,address)
{
this.r=rollno,
this.n=name,
this.a=address
this.show= function (){
console.log("Rollno ="+this.r+"name= "+this.n);
}
}
var st1= new Students(1,"abc","chandigrah")
st1.show()
var st2=new Students(2,"def","mohali")
st2.show()
</script>
</body>
</html>
Use of this is explained in upcoming
slides
Array
JavaScript Arrays are the objects that can store
multiple items(or values) irrespective of their
data types under a single variable. In fact, Arrays
don't just provide a way to store multiple values,
they also provide a way to access them randomly
in constant time(that is O(1) time complexity).
But in JavaScript, we have the freedom of storing
any data type value in an array be
it number, string, null, undefined, float, or even
an array can be stored inside an array.
Non-Primitive datatype
Array Type
Javascript arrays can be declared by three methods:
1. By array literal:
In this method, arrays are declared using const, let, or var keywords and
the values are assigned to them using [].
Syntax:
let ar = ['1','2','3'];
2. Constructor method:
Arrays can be declared by calling Array() constructor using the new
keyword.
//By constructor
let Y = new Array('Apple', 'Orange', 'Grapes', 'Banana');
var ar=[1,2,3,4,5];
for(var i=0;i<ar.length;i++)
console.log(ar[i]);
var std =new Array()
std[0]="hi";
std[1]=2
std[2]="2"
console.log(std[1]);
console.log(typeof std[2])
Array Methods
1. Push:
To add elements to the end of an array.
Syntax:
arr.push(element);
2. Pop:
To remove elements from the end of the array.
Syntax:
arr.pop()
3. Shift:
shift:
To remove elements at the beginning of the
array.
Syntax:
arr.shift()
4. unShift:
unsshift:
To add elements at the beginning of the array.
Syntax:
arr.unshift(“Element”)
Remove an Item by the Index Position
The splice() method can be used to remove, add
or even replace an element(s) in the array.
Remove: marks.splice(1, 1);
Add: marks.splice(2, 0, "newTwo", "newThree",
"newFour");
2 is the index from where the operation starts.
0 indicates that zero elements will be removed, that is, no
removal of elements.
Replaced: If 0 is replace by 1 indicates that zero elements
will be removed, that is, no removal of elements.(replaced)
Nested Objects and Arrays use in object Data type
Regular Expression
The RegExp in javascript is an object which is used to match a
string with a particular pattern.
Regular Expressions (RegExp) can be created by two methods:
1 . By using forward slashes:
In this method, we declare literals and then assign them the pattern which
follows a forward slash, and it is followed by a modifier.
Syntax:
let re = /pattern/modifier;
https://regexr.com/
Create custom
regular expression
Non- Primitive datatype
Regular Expression
2. By Constructor:
Regular expressions can be declared by calling RegExp() constructors
by passing the pattern as a parameter.
Syntax:
let re = new RegExp('pattern');
RegExp modifiers:
Modifiers are added after the declaration of
RegExp. Their task is to modify the search
operation according to their property.
Following are some common modifiers in
Javascript:
g: It is added to make sure the RegExp
doesn't stop after finding the first match. It
performs global matches.
i: It performs a case-insensitive matching.
m: It performs multiline matching.
Non-Primitive datatype
VAR VS LET VS CONST
let can be updated but not re-declared.
let greeting = "say Hi";
let greeting = "say Hello instead";//error
This fact makes let a better choice than var. When using let, you don't have to bother if
you have used a name for a variable before as a variable exists only within its scope.
let greeting = "say Hi";
if (true) {
let greeting = "say Hello instead";
console.log(greeting); // "say Hello instead"
}
console.log(greeting); // "say Hi"
const cannot be updated or re-declared
This means that the value of a variable declared with const remains the
same within its scope. It cannot be updated or re-declared. So if we declare
a variable with const, we can neither do this:
const greeting = "say Hi";
greeting = "say Hello instead";// error: Assignment to constant variable
TYPE CONVERSION
Type Conversion in JavaScript
Type conversion in JavaScript is the conversion of one data type to another
type (such as string to a number, object to a boolean, and so on) which is
required by the function or operator to work in the right way to give the
expected results.
Type conversions take place when any operation is done with different data
types, these conversions can be either done by the javascript compiler or
manually by us.
// Number is converted into String
console.log('5' + 3); // '53'
// String is converted into Number for calculation
console.log('5' - 3); // 2
console.log('5' * 3); // 15
// expression is converted into boolean
console.log(null == 1); // false
// When the result is not a number
console.log('Ale' - 2021); // NaN
Types of type conversion in Javascript
Basically, there are two ways in which type conversion in Javascript takes
place : Implicit and Explicit type conversions.
•Implicit type conversions - Automatic type conversion done by javascript
compiler.
•Explicit type conversions - Manual type conversion done by us.
Number() Boolean(), String(), Number(), parseInt(),
console.log(parseInt(65.456)); // 65
// Implicit conversion to string
'25' + 15; // '2515'
// Implicit conversions to a number
23 * '2'; // 46
23 - true; // 22 // true is converted into 1
true - null; // 1
false + undefined; // NaN // undefined into NaN
// Explicit conversions solved previous problem
const pensInBag = Number(prompt('How many pens you have in your bag?'));
const pensInHand = 10;
const totalPens = pensInHand + pensInBag;
console.log(totalPens);
// here now if i enter 5 then
// result appeared as expected: 15
// conversion to string using String()
String(2 - true); // '1'
'56' === String(56); // true
// conversion to number using Number()
Number(prompt()); // converts prompt value into a Number
Number('2350e-2'); // '23.5'
Number('23') + 7; // 30
// conversion to Boolean Explicitly
Boolean(''); // false
Boolean(2) == true; //true
2 + 3 + '4' + 'number'
OBJECT
The constructor() is a method used to initialize the object
properties. It is executed automatically when a new object of
the given class is created. (It may take parameters)
The constructor() is a method used to initialize the attributes in
Javascript classes. When an object is created, its class's
constructor() method is called.
The this keyword in Javascript is used to refer to the current
object in a method or constructor. It is used to stamp out the
confusion between class attributes and parameters that are
passed to the constructor with the same name.
class Student{
constructor(firstName, lastName, age, rollNo){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.rollNo = rollNo;
}
}
The constructor parameters are the values passed by the
user while creating an object which is assigned to the
class attributes.
The class attributes and the constructor parameters can
have different names, although it is a common practice to
write similar names for both.
The object in Javascript is a standalone entity created by the user
that has properties and types. It can be defined as the physical
entity built upon a class definition.
var s1 = new Student('Peter', 'Parker', 16, 48);
The new keyword in JavaScript creates an instance of an
object that has a constructor function.
Knowledge Base
The this keyword in Javascript is used to refer to the current
object in a method or constructor. It is used to stamp out the
confusion between class attributes and parameters that are
passed to the constructor with the same name.
The object in Javascript is a standalone entity created by the user
that has properties and types. It can be defined as the physical
entity built upon a class definition.
var s1 = new Student('Peter', 'Parker', 16, 48);
The new keyword in JavaScript creates an instance of an
object that has a constructor function.
Knowledge Base
What is this?
In JavaScript, the this keyword refers to an object.
The this keyword refers to different objects depending
on how it is used:
In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
Object
Object
An object is an unordered collection of data. It is an entity having state and behavior properties and
methods. For example, pen, chair, car, etc.…
Date Object
The JavaScript date object can be used to get year, month and day. You can display a timer on the
webpage using the JavaScript date object. It stores date and time.
Date Object
The JavaScript date object can be used to get year, month and day. You can
webpage using the JavaScript date object. It stores date and time.
Uses of Date Object
•Creation/Modification of time
•To display the current date and time
•To measure time
To create a date object using the ‘new’ keyword.
•new Date ()
•new Date (milliseconds)
•new Date (date string)
•new date (date, month, year, hour, minutes, seconds, milliseconds)
1.<!DOCTYPE html>
2.<html>
3.<head>
4. <title>Date Object in JavaScript</title>
5.</head>
6.<body>
7. <h2>Date Object in JavaScript</h2>
8. <h3>To Display the Current Date</h3>
9. <script type="text/javascript">
10. var date=new Date(); //to disp
lay current date
11. var day=date.getDate();
12. var month=date.getMonth()+1; //
It Starts with zero
13. var year=date.getFullYear();
14. document.write("<br>Current Dat
e is: "+day+"/"+month+"/"+year);
15. </script>
16.</body>
17.</html>
1.<!DOCTYPE html>
2.<html>
3.<head>
4. <title>Date Object in JavaScript</title
>
5. <meta charset="utf-8">
6.</head>
7.<body>
8. <h2>Date Object in JavaScript</h2>
9. <h3>To Display the Current Time</h3>
10. <script type="text/javascript">
11. var today =new Date();
12. var hour=today.getHours(); //curr
ent time
13. var minute=today.getMinutes();
14. var second=today.getSeconds();
15. document.write("Current Time is :"
+hour+":"+minute+":"+second);
16.</script>
17.</body>
18.</html>
1.<!DOCTYPE html>
2.<html>
3.<head>
4. <title>Date Object in JavaScript</title>
5. <meta charset="utf-8">
6.</head>
7.<body>
8. <h2>JavaScript set method</h2>
9. <script type="text/javascript">
10. function alerts()
11. {
12. alert("Hello! Welcome.");
13. }
14. setInterval(alerts,5000)
15.</script>
16.</body>
17.</html>
Setinterval () method
This will call the alert function every 5 seconds (1000 ms =
1 second).
Methods Description
sqrt(x) Returns the square root of x
log(x)
Returns the natural logarithm (base E) of
x
exp(x) Returns the value of Ex
pow(x,y) Returns the value of x to the power of y
abs(x) Returns the absolute value of x
random()
Returns a random number between 0
and 1
The Math Object Method
The Math object contains a number of methods that are used for calculations. There are some methods below:
FUNCTIONS
Functions
Functions
Anonymous functions
Anonymous functions are the functions that do not have any
name. Here, we use only the function keyword without the
function name. We can basically call an anonymous function by
assigning it to a variable and calling that variable.
Example:
let x = function (){ //anonymous function
console.log("I'm anonymous function!");
};
x(); //to call the anonymous function.
Functions
Arrow Functions
As of ES2015, we can also use arrow functions in place of function
expressions. Arrow function expressions are somewhat a compact
alternative to the normal function expressions; however, they are
restricted and cannot be used for all situations.
Demonstration of arrow functions:
const add = (a,b) => {
return a+b;
}
console.log(add(10,5)); // expected output: 15
Functions
When are function expressions
useful?
Function expressions are most useful
when:
1.We want to pass a function as an
argument to another function.
2.We want to use our functions as
As we know, JavaScript Functions are
first-class citizens; we can obviously
functions as arguments or assign them
a variable.
Example:
const a = function() {
console.log('I am from function
expression - a');
};
//function b is expecting a function as
parameter
function b(a){
console.log('Hey I am from function - b');
a();
}
b(a); //Function expression 'a' is passed
as an argument to 'b'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<textarea name="" id="txt" cols="30" rows="10" onfocus="back1()" onblur="back2()"></textarea>
<button onclick="copy()">Submit</button>
<p id="copy"></p>
</body>
<script>
function back1(){
document.getElementById("txt").style.backgroundColor="lightgrey"
}
function back2(){
document.getElementById("txt").style.backgroundColor=""
}
function copy()
{
let text= document.getElementById("txt").value
document.getElementById("copy").innerHTML=text
}
</script>
</html>
Functions(function passed as argument)
<script>
let ad=()=>{ var a=10;return (a) //arrow function
}
function add(value){
ac=50;
bc=20;
console.log("value ac: "+(ac+bc)+" value of a in arrow fn "+value()) //value of a in
arrow function is printed
return ac;
}
var z =add(ad) // function call ad is pass as function argument
console.log("value returned is"+z)//value of ac
</script>
Mouse Events
Event Occurs When
onclick A user clicks on an element
oncontextmenu A user right-clicks on an element
ondblclick A user double-clicks on an element
onmousedown A mouse button is pressed over an element
onmouseleave The mouse pointer moves out of an element
onmousemove The mouse pointer moves over an element
onmouseout The mouse pointer moves out of an element
onmouseover The mouse pointer moves onto an element
onmouseup A mouse button is released over an element
Sum(event)
Sum(e)
{
document.getElementById("result").inner
HTML=e.button
document.getElementById("result").inner
HTML=e.details
}
Keyboard Events
Event Occurs When
onkeydown A user presses a key
onkeypress A user presses a key
onkeyup A user releases a key
The onkeypress event is deprecated.
It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers.
To detect if the user presses a key, always use the onkeydown event.
It works for all keys.
</script>
<input type="text"
onkeypress="myFunction(event)">
<script>
function myFunction(e) {
document.write(e.key)
}
<body>
<button value="a">A</button>
<button>B</button>
<button>C</button>
<p></p>
Using anonymous function or function and then this keyword give access to the
object it is refering
Using arrow function and then this
keyword , you can access window object
Event Listener(calculator )
<body>
<input type="text" id="n1"
placeholder="Enter number 1" value="0">
<input type="text" name="" id="n2"
placeholder="Enter number 2" value="0">
<img src="" alt="">
<p id="result"></p>
<button id="btn">+</button>
<button id="btn">-</button>
for(i=0;i<document.querySelectorAll("#btn").length;i++)
{
document.querySelectorAll("button")[i].addEventListener(
"click",function (){
var n1=Number(document.querySelector("#n1").value);
var n2=Number(document.querySelector("#n2").value);
var opertor=this.innerHTML
switch(opertor)
{
case '+':
console.log(n1+n2)
break;
case '-':
console.log(n1-n2)
break;
default:
console.log("not a valid operator"); })
</script>
Event Listener(play audio with button click and keyboard keys )
<body>
<div class="keys">
<button value="a">A</button>
<button value="s">S</button>
<button value="d">D</button>
<button value="f">F</button>
</div>
function song(k){
switch(k)
{
case 'A': var s= new Audio("/sounds/do-80236.mp3")
s.play();
break
case 'S': var s= new Audio("/sounds/g6-82013.mp3")
s.play();
break
case 'D': var s= new Audio("/sounds/sol-
101774.mp3")
s.play();
break
}
}
</script>
<script>
for (var i = 0; i <
document.querySelectorAll("button").length; i++) {
document.querySelectorAll("button")[i].addEventListener(
"click",keychk)
function keychk()
{
k=this.innerHTML
song(k)
}
}
document.addEventListener("keypress", cap)
function cap(){
console.log(event.key)
song(event.key)
}
DOM Model
JS HTML Data Object Model
DOM
With the HTML DOM,
JavaScript can access and
change all the elements of
an HTML document.
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:
Data Object Model
Data Object Model
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
Data Object Model
You Will Learn
• How to change the content of HTML elements
• How to change the style (CSS) of HTML elements
• How to react to HTML DOM events
• How to add and delete HTML elements
Data Object Model
What is the HTML DOM?
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.
Data Object Model
HTML DOM methodsare actions you can perform (on
HTML Elements).
HTML DOM propertiesare values (of HTML Elements)
that you can set or change.
Data Object Model
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
getElementById method used id="demo" to find the element.
innerHTML property is useful for getting or replacing the content of HTML elements.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you
always start with accessing the document object.
Changing HTML Elements
Adding and Deleting Elements
const para = document.createElement("p");
para.innerText = "This is a paragraph";
document.body.appendChild(para);
Adding Events Handlers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling</title>
</head>
<body>
<button>A</button>
<button>B</button>
<button id="btn">C</button>
<button>d</button>
<button>e</button>
<button id="btn2">f</button>
</body>
<script>
for(var i=0;i<document.querySelectorAll("button").length;i++)
{
document.querySelectorAll("button")[i].addEventListener("click",show)
function show()
{
console.log(this.innerHTML)
}
}
Node (DOM)
In the context of the DOM, a node is a single point in the node tree. Various
things that are nodes are the document itself, elements, text, and comments.
.append()
This method is used to add an element in form of a Node object or a
DOMString (basically means text).
.appendChild()
Similar to the .append method, this method is used to elements in the
DOM, but in this case, only accepts a Node object.
// Inserting a DOMString
const parent = document.createElement('div');
parent.append('Appending Text');
// The div would then look like this <div>Appending
Text</div>
const parent = document.createElement('div');
parent.appendChild('Appending Text');
// Uncaught TypeError: Failed to execute
'appendChild' on 'Node': parameter 1 is not of
type 'Node'
</body>
<script>
// head= document.createElement("h1")
// document.body.appendChild(head)
// head.innerHTML="Article"
const head=document.createElement("h1")
const headtext=document.createTextNode("Article")
head.appendChild(headtext)
document.body.appendChild(head)
()
</script>
Method 1, but not a valid way
Method 2,valid way
</script>
head=document.createElement("div")
child=document.createElement("p")
t=document.createTextNode("the value of paragraph")
child.appendChild(t)
head.appendChild(child)
document.body.appendChild(head)
</script>
head=document.createElement("div")
child=document.createElement("p")
// t=document.createTextNode("the value of
paragraph")
child.append("this is text inside paragraph")
head.appendChild(child)
document.body.appendChild(head)
body>
<ul id="list">
</ul>
<button onclick="add()">Add LI item</button>
</body>
<script>
var count=0;
function add(){
let liitem= document.createElement("li")
litext=document.createTextNode("item"+count)
liitem.appendChild(litext)
document.getElementById("list").append(liitem)
count++
}
Adds li item when button Is
clicked
Local Storage
localStorage is a property that allows JavaScript sites and apps
to save key-value pairs in a web browser with no expiration
date. you can store small amounts of data with localStorage, it’s
not suitable for large amounts of data. localStorage is accessible
to anyone who uses the device, Both sessionStorage and
localStorage maintain a separate storage area for each available
origin for the duration of the page session. The main difference
between them is that sessionStorage only maintains a storage
area. At the same time, the browser is open (including when
the page reloads or restores) while localStorage continues to
store data after the browser is closed.
setItem(): Add key and value to localStorage
getItem(): This is how you get items from localStorage
removeItem(): Remove an item from localStorage
clear(): Clear all data from localStorage
key(): Passed a number to retrieve the key of a localStorage
<form action="" ">
<input type="text" name="text" id="txt">
<input type="email" name="email" id="eml">
<input type="submit" name="" id="sbmit" onclick="str(event)">
</form>
<script>
let count=0
function str(event){
event.preventDefault();
const username=document.getElementById("txt").value
const useremail=document.getElementById("eml").value
const data={
name: username,
email:useremail
}
localStorage.setItem(`data${count}`,JSON.stringify(data))
count++;
}
</script>
Set item in local storage
Output
Filter array that contains specific pattern
keys=Object.keys(localStorage)
['data2', 'data1', 'user', 'data0']
var pattern=/data/
filtered=keys.filter(function(k){ return pattern.test(k)})
['data2', 'data1', 'data0']
Example of filter method
<body onload="show()">
<dl id="userdata">
<dt>Username</dt>
<dt>Email</dt>
</dl>
<script>
function show(){
keys=Object.keys(localStorage)
let pattern=/data/
const fdata=keys.filter(ptr)
function ptr(k)
{
return pattern.test(k)
}
console.log(fdata)
fdata.forEach(k => {
var f=JSON.parse(localStorage.getItem(k))
// let z=f.split(" ")
const usr=document.createElement("dd")
const eml=document.createElement("dd")
usr.append(f.name)
eml.append(f.email)
document.querySelectorAll("dt")[0].append(usr)
document.querySelectorAll("dt")[1].append(eml)
});
}
</script>
To show local storage data in other page
Using
onload to
show data
Output in other page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.article{
background-color: red;
color: white;
font-family: Georgia, 'Times New Roman', Times, serif;
font-size: 2rem;
}
</style>
</head>
<body>
<ul id="list">
</ul>
<button >click</button>
</body>
</html>
{
const anchor=
document.createElement("a")
const
li=document.createElement("li")
anchor.setAttribute("href","#")
li.append("item"+count)
anchor.append(li)
document.getElementById("list").
append(anchor)
count++
for(i=0;i<document.querySelectorAl
l("a").length;i++)
{
document.querySelectorAll("a")[i
].addEventListener("click",rm)
function rm()
{
this.remove()
}
Code of give task
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Social Share</title>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</head>
<body>
<textarea name="txtn" id="txtid" cols="30" rows="10"></textarea>
<button id="twitterShareButton">Share on Twitter</button>
<script>
document.getElementById('twitterShareButton').addEventListener('click',
function() {
var tweetText = document.getElementById("txtid").value // The text to be shared
on Twitter
var twitterShareUrl = 'https://twitter.com/intent/tweet?text=' +
encodeURIComponent(tweetText)
// Open the Twitter share dialog
window.open(twitterShareUrl, '_blank', 'width=550,height=420');
});
</script>
Twitter share
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-
scale=1.0">
<title>Search</title>
</head>
<body>
<input type="search" name="" id="search">
<ul id="list">
<li>computer</li>
<li>hardware</li>
<li>software</li>
<li>css</li>
<li>html</li>
</ul>
</body>
</html>
<script>
document.querySelector("#list").style.display=""//ch
ange value to "none" to hide list"
document.querySelector("#search").addEventListener("
input",chk)
function chk()
{
searchvalue=document.getElementById("search").value;
listarry=document.querySelectorAll("li");
for(i=0;i<listarry.length;i++)
{
list=listarry[i].textContent
if(list.includes(searchvalue))
{
document.querySelector("#list").style.di
splay=''
listarry[i].style.display=''
}
else{
listarry[i].style.display="none"
}
}
if(searchvalue=='')
{
document.querySelector("#list").style.display=""
//change value to "none" to hide the list after
input is deleted
}
Search text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Game</title>
<style>
#container{
width: 100%;
height: 300px;
background-color: black;
}
#box{
width: 30px;
height: 30px;
background-color: white;
position: relative;
left: 1px;
top: 1px;
transition: left, top;
}
</style>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>
<script>
let posl=1
let post=1
document.addEventListener("keypress",move)
function move(event)
{
let presskey=event.key
presskey=presskey.toLowerCase()
let box=document.getElementById("box")
if(presskey=="a")
{
console.log(presskey)
box.style.left= posl+"px"
posl=posl-10
}
else if(presskey=="s")
{
console.log(presskey)
box.style.top=post+"px"
post=post+10
}
else if(presskey=="d")
{
console.log(presskey)
box.style.left=posl+"px"
posl=posl+10;
}
else if(presskey=="w")
Move white
box with a,s,d,f
keys
Social sharing Buttons
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
/script>
head>
ody>
<li id="btn"><a href="#">Home</a></li>
<div id="list">
<p>Course Offered</p>
<li>C</li>
<li>HTML</li>
<li>CSS</li>
<li>JAVA</li>
<li>JQUERY</li>
</div>
<input id="txt">
<button value="wa">whatsapp</button>
<button value="fb">Facebook</button>
<button value="tw">Twitter</button>
<style>
body{
background-color: cadetblue;
}
#list{
background-color: lightgrey;
width: 25%;
position: absolute;
display: none;
}
#list > li{
list-style-type: none;
padding: 10px;
border: 1px solid red;
font-size: .7rem;
cursor: pointer;
}
#list p{
font-size: 1rem;
}
.submenu
{
display: none;
}
.clr{
background-color: black;
color: white;
}
.clsadd{
background-color: tomato;
color: white;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
</style>
for(i=0;i<document.querySelectorAll("button").length;i++)
{
document.querySelectorAll("button")[i].addEventListener("click",function(){
let btn=this.value
let share=document.getElementById("txt").value;
if (btn=="wa")
{
let url= 'https://api.whatsapp.com/send?text='+ encodeURIComponent(share)
win(url);
}
if (btn=="tw")
{
let url= 'https://twitter.com/intent/tweet?text='+ encodeURIComponent(share)
win(url);
}
if(btn=="fb")
{
// Get the value of the text box
// Encode the value for URL
var encodedValue = encodeURIComponent(share);
// Generate the Facebook share URL with the encoded value
var shareURL = `https://www.facebook.com/dialog/feed?app_id=994589648635629&quote${share}` + encodedValue;
// Open the Facebook share dialog in a new window
window.open(shareURL, '_blank');
}
if(btn=="in")
{
let url= 'https://www.instagram.com/create/story'
win(url);
}
function win(url)
{
window.open(url,'_blank','width=320px,height=420px')
}
})
https://vercel.com/new
For hosting your website
https://www.emailjs.com/
Send email using js

More Related Content

Similar to js.pptx

Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript ProgrammingRaveendra R
 
Java script Basic
Java script BasicJava script Basic
Java script BasicJaya Kumari
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTAAFREEN SHAIKH
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java ProgrammingRaveendra R
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java scriptnanjil1984
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxTusharTikia
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptxAlkanthiSomesh
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Lookrumsan
 

Similar to js.pptx (20)

copa-ii.pptx
copa-ii.pptxcopa-ii.pptx
copa-ii.pptx
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
Javascript
JavascriptJavascript
Javascript
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
chap04.ppt
chap04.pptchap04.ppt
chap04.ppt
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
Java script
Java scriptJava script
Java script
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
Java script
Java scriptJava script
Java script
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Java scipt
Java sciptJava scipt
Java scipt
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 

Recently uploaded

Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxhublikarsn
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Query optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsQuery optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsmeharikiros2
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)ChandrakantDivate1
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...ppkakm
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...ronahami
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfsumitt6_25730773
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessorAshwiniTodkar4
 

Recently uploaded (20)

Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptx
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Query optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsQuery optimization and processing for advanced database systems
Query optimization and processing for advanced database systems
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 

js.pptx

  • 2. JAVASCRIPT •In September 1995, Brendan Eich, a programmer at Netscape developed a programming language in just 10 days. •This language was initially called Mocha, then LiveScript. •In December 1995 Netscape and Sun(the organisation that owned Java) had a license agreement regarding Javascript(then LiveScript) hence it was renamed to Javascript and specifically "Java" script because Java was the most popular language at that time and this would help the marketing of Javascript as well. History ECMA International European Computer Manufacturers Association (ECMA) is a nonprofit standards organization for information and communication systems. It acquired its current name in 1994, when the European Computer Manufacturers Association (ECMA) changed its name to reflect the organization's global reach and activities. Offical name of java scripy
  • 3. JAVASCRIPT Applications of JavaScript Excellent user interactivity: Javascript, it allows users to interact with the webpage allowing us to build amazing websites and web apps. Web and Mobile app creation: Javascript based frameworks like React, Angular, Vue allow us to build robust web applications. Server-side development: We can also use Javascript to develop the back end infrastructure of a web application by using Node.js.Example: Netflix, Game development: Javascript can also be used to develop browser based games some of them are HexGL, CrossCode, etc. Art: We can also make digital art on the HTML5 canvas by using javascript based libraries.Example.js library
  • 4. JAVASCRIPT Applications of JavaScript Client-side use of JavaScript Javascript is mostly used for client-side scripting. (Code is run on the client's browser) It can be used to modify the web page’s user interface (the browser and its DOM) and make pages interactive. It deals with client-side processing like cookies, sessions. It deals with the storage of the web browser i.e. local and session storage. For example: If the user selects a dark theme for a website once, the website is always in dark theme whenever the user re-visits the page, this is because the user's preference is stored in local storage by Javascript.
  • 5. JAVASCRIPT server side use of JavaScript Javascript can also be used to for server side development. This is possible because of Node.js. Node.js is an application runtime environment that allows us to use JavaScript for building server-side applications. We can do things like database queries, network requests, files on the server, running web servers, interacting with other servers, handling data sent to the server, etc. Server side scripting is responsible for showing dynamic content on the webpage.
  • 6. JAVASCRIPT How to Insert JavaScript into an HTML Page You can insert a JavaScript program into an HTML document in two ways. •Internal JavaScript •External JavaScript Both methods make use of the <script> tag
  • 7. JAVASCRIPT <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="/javascript.js"></script> </head> <body> <script> console.log("Hello World!") </script> </body> </html>
  • 8. 3 Ways of Printing Using console.log() The console.log() is a function used to log messages on the web console Using document.write() document.write() is another function you can use to print Hello World in JavaScript. Using alert() The last function we will use to print Hello World in JavaScript is alert. This function displays a pop-up box over the current window with the specified message .Using cofirm() creates a popup that contains two buttons ok and cancel.Where on clicking ok button contains boolean true value and cancel contains Boolean false value Using prompt()// creates a popup that is used to take input from the user
  • 9. Using async and defer async and defer are <script> tag attributes that can be used to increase website loading times. With async, the file gets downloaded asynchronously and then executed as soon as it’s downloaded. With defer, the file gets downloaded asynchronously but executed only when the document parsing is completed. <script async src="script.js"></script>
  • 10.
  • 12. Declaring variables Declaring a Variable One must create a variable before using it. In programming terms, we call this declaring a variable. In Javascript, we can declare a variable using either let, var, or const keywords. To declare a variable without using any keyword, we have to just write the variable name and must assign a value to that variable. On doing this, the variable becomes a global variable However, it is not recommended to declare a variable without using var as it may alter the of an already existing global variable
  • 13. variables Rules/Identifiers While Declaring a JavaScript Variable To declare a JavaScript variable, one must know the rules to follow, Rules are as follows: •Variables are case-sensitive in JavaScript. •We can use letters, digits, and symbols like a dollar sign ($) and underscore _ in a variable name. •We cannot start a variable name with a digit (0-9). •We cannot use any of the reserved keywords (function, return, type of, break, etc.) of JavaScript as a variable name.
  • 14. Var and let The Difference Between 'var' and 'let’ 1. The main difference between var and let is that the scope of the variable is defined by let is limited to the block in which it is declared, whereas the variable declared using var has a global scope, i.e., can be used throughout the code 2. We cannot declare the same variable multiple times if one of them is using let, whereas we can declare the same variable any number of times using var. let myName = "my name"; let myName = "not my name"; console.log(myName); //output => SyntaxError: redeclaration of let name
  • 15. 1. JavaScript Reserved Words break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with
  • 17. What are Data Types in JavaScript? There are mainly two types of data types in JavaScript: 1.Primitive data types. 2.Non-primitive data types. Primitive Data Types in JavaScript Primitive data types in javascript refer to those data types that are defined the most basic level of the language. There are 7 primitive data types in JavaScript: 1.Numbers 2.BigInt 3.String 4.Boolean 5.Undefined 6.Null 7.Symbol Largest safe Integer: It represents the largest integer value that can be represented by javascript without any overflow. Representation: Number.MAX_SAFE_I NTEGER Value: 253 - 1 or 9007199254740991 Data types
  • 18.
  • 19. Boolean Type It can be declared by using the bool keyword followed by the variable name. It can be assigned only two values, true or false. Syntax: bool flag = false; Primitive datatype
  • 20. Symbol Data type One of the reasons of adding the data type was to enable private properties in JavaScript. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object Primitive datatype
  • 21. String properties: 1. Indexing 2. Immutability: let name = ‘abcd’; name.toLowerCase(); // INVALID OPERATION solution: let newName = name.toLowerCase(); console.log(newName); 3. Concatenation: var str3 = str1 + str2; 4. str.charAt(index); 5. By using the backslash character We can also break the string into multiple lines using backslashes (). Primitive datatype
  • 22. Method Description charAt() Finds the character present at a particular index in the string. concat() Concatenates the string arguments. indexOf() returns the index of the first occurrence of the passed value. lastIndexOf() returns the index of the last occurrence of the passed value. toLowerCase() converts all the characters of the string into lowercase letters. toUpperCase() converts all the characters of the string into uppercase letters. split() divides the given string into an ordered list of substrings. trim() removes additional spaces around the string. toString() returns a string object as a string. substring() extracts the characters between two indices of a string and returns a substring. slice() .length extracts a section of a string and returns it as a new string, without modifying the original string.
  • 23.
  • 24. What are Data Types in JavaScript? There are mainly two types of data types in JavaScript: 1.Primitive data types. 2.Non-primitive data types. Non-primitive Data Types in JavaScript Non-primitive data types are those data types that aren't defined at a basic but are complex data types formed upon operations with primitive data types. There are mainly 3 types of non-primitive (or complex) data types in JavaScript: 1.Object 2.Array 3.RegExp Non-Primitive datatype
  • 25.
  • 26. Declaration: Object in javascript is a collection of data that is kept in a key-value pair manner. Objects in javascript can be created by two methods: 1. Literal method: let obj = { key: "value" } 2. By constructor method let obj=new Object(); obj.name='javascript' console.log(obj); obj.course="hi"; console.log(obj); <script> let phone=Symbol("ph"); let phone2=Symbol("ph"); let students={ rollno:"1", name:"abc", age:" 20", students[phone]=1234; }; students[phone2]=3456; students.gender="male"; console.log(students) JSON.stringify(students) </script> <script> let students={ rollno:"1", name:"abc", age:" 20", }; students.gender="male"; console.log(students) </script> Non-Primitive datatype
  • 27. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> </head> <body> <script> function Students(rollno,name,address) { this.r=rollno, this.n=name, this.a=address this.show= function (){ console.log("Rollno ="+this.r+"name= "+this.n); } } var st1= new Students(1,"abc","chandigrah") st1.show() var st2=new Students(2,"def","mohali") st2.show() </script> </body> </html> Use of this is explained in upcoming slides
  • 28. Array JavaScript Arrays are the objects that can store multiple items(or values) irrespective of their data types under a single variable. In fact, Arrays don't just provide a way to store multiple values, they also provide a way to access them randomly in constant time(that is O(1) time complexity). But in JavaScript, we have the freedom of storing any data type value in an array be it number, string, null, undefined, float, or even an array can be stored inside an array. Non-Primitive datatype
  • 29. Array Type Javascript arrays can be declared by three methods: 1. By array literal: In this method, arrays are declared using const, let, or var keywords and the values are assigned to them using []. Syntax: let ar = ['1','2','3']; 2. Constructor method: Arrays can be declared by calling Array() constructor using the new keyword. //By constructor let Y = new Array('Apple', 'Orange', 'Grapes', 'Banana'); var ar=[1,2,3,4,5]; for(var i=0;i<ar.length;i++) console.log(ar[i]); var std =new Array() std[0]="hi"; std[1]=2 std[2]="2" console.log(std[1]); console.log(typeof std[2])
  • 30. Array Methods 1. Push: To add elements to the end of an array. Syntax: arr.push(element); 2. Pop: To remove elements from the end of the array. Syntax: arr.pop() 3. Shift: shift: To remove elements at the beginning of the array. Syntax: arr.shift() 4. unShift: unsshift: To add elements at the beginning of the array. Syntax: arr.unshift(“Element”) Remove an Item by the Index Position The splice() method can be used to remove, add or even replace an element(s) in the array. Remove: marks.splice(1, 1); Add: marks.splice(2, 0, "newTwo", "newThree", "newFour"); 2 is the index from where the operation starts. 0 indicates that zero elements will be removed, that is, no removal of elements. Replaced: If 0 is replace by 1 indicates that zero elements will be removed, that is, no removal of elements.(replaced)
  • 31. Nested Objects and Arrays use in object Data type
  • 32. Regular Expression The RegExp in javascript is an object which is used to match a string with a particular pattern. Regular Expressions (RegExp) can be created by two methods: 1 . By using forward slashes: In this method, we declare literals and then assign them the pattern which follows a forward slash, and it is followed by a modifier. Syntax: let re = /pattern/modifier; https://regexr.com/ Create custom regular expression Non- Primitive datatype
  • 33. Regular Expression 2. By Constructor: Regular expressions can be declared by calling RegExp() constructors by passing the pattern as a parameter. Syntax: let re = new RegExp('pattern'); RegExp modifiers: Modifiers are added after the declaration of RegExp. Their task is to modify the search operation according to their property. Following are some common modifiers in Javascript: g: It is added to make sure the RegExp doesn't stop after finding the first match. It performs global matches. i: It performs a case-insensitive matching. m: It performs multiline matching. Non-Primitive datatype
  • 34.
  • 35. VAR VS LET VS CONST
  • 36.
  • 37. let can be updated but not re-declared. let greeting = "say Hi"; let greeting = "say Hello instead";//error This fact makes let a better choice than var. When using let, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope. let greeting = "say Hi"; if (true) { let greeting = "say Hello instead"; console.log(greeting); // "say Hello instead" } console.log(greeting); // "say Hi"
  • 38. const cannot be updated or re-declared This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can neither do this: const greeting = "say Hi"; greeting = "say Hello instead";// error: Assignment to constant variable
  • 40. Type Conversion in JavaScript Type conversion in JavaScript is the conversion of one data type to another type (such as string to a number, object to a boolean, and so on) which is required by the function or operator to work in the right way to give the expected results. Type conversions take place when any operation is done with different data types, these conversions can be either done by the javascript compiler or manually by us.
  • 41. // Number is converted into String console.log('5' + 3); // '53' // String is converted into Number for calculation console.log('5' - 3); // 2 console.log('5' * 3); // 15 // expression is converted into boolean console.log(null == 1); // false // When the result is not a number console.log('Ale' - 2021); // NaN
  • 42. Types of type conversion in Javascript Basically, there are two ways in which type conversion in Javascript takes place : Implicit and Explicit type conversions. •Implicit type conversions - Automatic type conversion done by javascript compiler. •Explicit type conversions - Manual type conversion done by us. Number() Boolean(), String(), Number(), parseInt(), console.log(parseInt(65.456)); // 65
  • 43. // Implicit conversion to string '25' + 15; // '2515' // Implicit conversions to a number 23 * '2'; // 46 23 - true; // 22 // true is converted into 1 true - null; // 1 false + undefined; // NaN // undefined into NaN
  • 44. // Explicit conversions solved previous problem const pensInBag = Number(prompt('How many pens you have in your bag?')); const pensInHand = 10; const totalPens = pensInHand + pensInBag; console.log(totalPens); // here now if i enter 5 then // result appeared as expected: 15
  • 45. // conversion to string using String() String(2 - true); // '1' '56' === String(56); // true // conversion to number using Number() Number(prompt()); // converts prompt value into a Number Number('2350e-2'); // '23.5' Number('23') + 7; // 30 // conversion to Boolean Explicitly Boolean(''); // false Boolean(2) == true; //true 2 + 3 + '4' + 'number'
  • 47. The constructor() is a method used to initialize the object properties. It is executed automatically when a new object of the given class is created. (It may take parameters) The constructor() is a method used to initialize the attributes in Javascript classes. When an object is created, its class's constructor() method is called. The this keyword in Javascript is used to refer to the current object in a method or constructor. It is used to stamp out the confusion between class attributes and parameters that are passed to the constructor with the same name. class Student{ constructor(firstName, lastName, age, rollNo){ this.firstName = firstName; this.lastName = lastName; this.age = age; this.rollNo = rollNo; } } The constructor parameters are the values passed by the user while creating an object which is assigned to the class attributes. The class attributes and the constructor parameters can have different names, although it is a common practice to write similar names for both. The object in Javascript is a standalone entity created by the user that has properties and types. It can be defined as the physical entity built upon a class definition. var s1 = new Student('Peter', 'Parker', 16, 48); The new keyword in JavaScript creates an instance of an object that has a constructor function. Knowledge Base
  • 48. The this keyword in Javascript is used to refer to the current object in a method or constructor. It is used to stamp out the confusion between class attributes and parameters that are passed to the constructor with the same name. The object in Javascript is a standalone entity created by the user that has properties and types. It can be defined as the physical entity built upon a class definition. var s1 = new Student('Peter', 'Parker', 16, 48); The new keyword in JavaScript creates an instance of an object that has a constructor function. Knowledge Base What is this? In JavaScript, the this keyword refers to an object. The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object. In a function, this refers to the global object.
  • 49. Object Object An object is an unordered collection of data. It is an entity having state and behavior properties and methods. For example, pen, chair, car, etc.… Date Object The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage using the JavaScript date object. It stores date and time.
  • 50. Date Object The JavaScript date object can be used to get year, month and day. You can webpage using the JavaScript date object. It stores date and time. Uses of Date Object •Creation/Modification of time •To display the current date and time •To measure time To create a date object using the ‘new’ keyword. •new Date () •new Date (milliseconds) •new Date (date string) •new date (date, month, year, hour, minutes, seconds, milliseconds)
  • 51. 1.<!DOCTYPE html> 2.<html> 3.<head> 4. <title>Date Object in JavaScript</title> 5.</head> 6.<body> 7. <h2>Date Object in JavaScript</h2> 8. <h3>To Display the Current Date</h3> 9. <script type="text/javascript"> 10. var date=new Date(); //to disp lay current date 11. var day=date.getDate(); 12. var month=date.getMonth()+1; // It Starts with zero 13. var year=date.getFullYear(); 14. document.write("<br>Current Dat e is: "+day+"/"+month+"/"+year); 15. </script> 16.</body> 17.</html> 1.<!DOCTYPE html> 2.<html> 3.<head> 4. <title>Date Object in JavaScript</title > 5. <meta charset="utf-8"> 6.</head> 7.<body> 8. <h2>Date Object in JavaScript</h2> 9. <h3>To Display the Current Time</h3> 10. <script type="text/javascript"> 11. var today =new Date(); 12. var hour=today.getHours(); //curr ent time 13. var minute=today.getMinutes(); 14. var second=today.getSeconds(); 15. document.write("Current Time is :" +hour+":"+minute+":"+second); 16.</script> 17.</body> 18.</html>
  • 52. 1.<!DOCTYPE html> 2.<html> 3.<head> 4. <title>Date Object in JavaScript</title> 5. <meta charset="utf-8"> 6.</head> 7.<body> 8. <h2>JavaScript set method</h2> 9. <script type="text/javascript"> 10. function alerts() 11. { 12. alert("Hello! Welcome."); 13. } 14. setInterval(alerts,5000) 15.</script> 16.</body> 17.</html> Setinterval () method This will call the alert function every 5 seconds (1000 ms = 1 second).
  • 53. Methods Description sqrt(x) Returns the square root of x log(x) Returns the natural logarithm (base E) of x exp(x) Returns the value of Ex pow(x,y) Returns the value of x to the power of y abs(x) Returns the absolute value of x random() Returns a random number between 0 and 1 The Math Object Method The Math object contains a number of methods that are used for calculations. There are some methods below:
  • 56. Functions Anonymous functions Anonymous functions are the functions that do not have any name. Here, we use only the function keyword without the function name. We can basically call an anonymous function by assigning it to a variable and calling that variable. Example: let x = function (){ //anonymous function console.log("I'm anonymous function!"); }; x(); //to call the anonymous function.
  • 57. Functions Arrow Functions As of ES2015, we can also use arrow functions in place of function expressions. Arrow function expressions are somewhat a compact alternative to the normal function expressions; however, they are restricted and cannot be used for all situations. Demonstration of arrow functions: const add = (a,b) => { return a+b; } console.log(add(10,5)); // expected output: 15
  • 58. Functions When are function expressions useful? Function expressions are most useful when: 1.We want to pass a function as an argument to another function. 2.We want to use our functions as As we know, JavaScript Functions are first-class citizens; we can obviously functions as arguments or assign them a variable. Example: const a = function() { console.log('I am from function expression - a'); }; //function b is expecting a function as parameter function b(a){ console.log('Hey I am from function - b'); a(); } b(a); //Function expression 'a' is passed as an argument to 'b'
  • 59. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <textarea name="" id="txt" cols="30" rows="10" onfocus="back1()" onblur="back2()"></textarea> <button onclick="copy()">Submit</button> <p id="copy"></p> </body> <script> function back1(){ document.getElementById("txt").style.backgroundColor="lightgrey" } function back2(){ document.getElementById("txt").style.backgroundColor="" } function copy() { let text= document.getElementById("txt").value document.getElementById("copy").innerHTML=text } </script> </html>
  • 60. Functions(function passed as argument) <script> let ad=()=>{ var a=10;return (a) //arrow function } function add(value){ ac=50; bc=20; console.log("value ac: "+(ac+bc)+" value of a in arrow fn "+value()) //value of a in arrow function is printed return ac; } var z =add(ad) // function call ad is pass as function argument console.log("value returned is"+z)//value of ac </script>
  • 61. Mouse Events Event Occurs When onclick A user clicks on an element oncontextmenu A user right-clicks on an element ondblclick A user double-clicks on an element onmousedown A mouse button is pressed over an element onmouseleave The mouse pointer moves out of an element onmousemove The mouse pointer moves over an element onmouseout The mouse pointer moves out of an element onmouseover The mouse pointer moves onto an element onmouseup A mouse button is released over an element Sum(event) Sum(e) { document.getElementById("result").inner HTML=e.button document.getElementById("result").inner HTML=e.details }
  • 62. Keyboard Events Event Occurs When onkeydown A user presses a key onkeypress A user presses a key onkeyup A user releases a key The onkeypress event is deprecated. It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers. To detect if the user presses a key, always use the onkeydown event. It works for all keys. </script> <input type="text" onkeypress="myFunction(event)"> <script> function myFunction(e) { document.write(e.key) }
  • 64. Using anonymous function or function and then this keyword give access to the object it is refering
  • 65. Using arrow function and then this keyword , you can access window object
  • 66. Event Listener(calculator ) <body> <input type="text" id="n1" placeholder="Enter number 1" value="0"> <input type="text" name="" id="n2" placeholder="Enter number 2" value="0"> <img src="" alt=""> <p id="result"></p> <button id="btn">+</button> <button id="btn">-</button> for(i=0;i<document.querySelectorAll("#btn").length;i++) { document.querySelectorAll("button")[i].addEventListener( "click",function (){ var n1=Number(document.querySelector("#n1").value); var n2=Number(document.querySelector("#n2").value); var opertor=this.innerHTML switch(opertor) { case '+': console.log(n1+n2) break; case '-': console.log(n1-n2) break; default: console.log("not a valid operator"); }) </script>
  • 67. Event Listener(play audio with button click and keyboard keys ) <body> <div class="keys"> <button value="a">A</button> <button value="s">S</button> <button value="d">D</button> <button value="f">F</button> </div> function song(k){ switch(k) { case 'A': var s= new Audio("/sounds/do-80236.mp3") s.play(); break case 'S': var s= new Audio("/sounds/g6-82013.mp3") s.play(); break case 'D': var s= new Audio("/sounds/sol- 101774.mp3") s.play(); break } } </script> <script> for (var i = 0; i < document.querySelectorAll("button").length; i++) { document.querySelectorAll("button")[i].addEventListener( "click",keychk) function keychk() { k=this.innerHTML song(k) } } document.addEventListener("keypress", cap) function cap(){ console.log(event.key) song(event.key) }
  • 69. JS HTML Data Object Model DOM With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
  • 70. 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: Data Object Model
  • 72. 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 Data Object Model
  • 73. You Will Learn • How to change the content of HTML elements • How to change the style (CSS) of HTML elements • How to react to HTML DOM events • How to add and delete HTML elements Data Object Model
  • 74. What is the HTML DOM? 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. Data Object Model
  • 75. HTML DOM methodsare actions you can perform (on HTML Elements). HTML DOM propertiesare values (of HTML Elements) that you can set or change. Data Object Model
  • 76. <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> In the example above, getElementById is a method, while innerHTML is a property. getElementById method used id="demo" to find the element. innerHTML property is useful for getting or replacing the content of HTML elements.
  • 77. The HTML DOM Document Object The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object.
  • 79. Adding and Deleting Elements const para = document.createElement("p"); para.innerText = "This is a paragraph"; document.body.appendChild(para);
  • 81. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Event Handling</title> </head> <body> <button>A</button> <button>B</button> <button id="btn">C</button> <button>d</button> <button>e</button> <button id="btn2">f</button> </body> <script> for(var i=0;i<document.querySelectorAll("button").length;i++) { document.querySelectorAll("button")[i].addEventListener("click",show) function show() { console.log(this.innerHTML) } }
  • 82. Node (DOM) In the context of the DOM, a node is a single point in the node tree. Various things that are nodes are the document itself, elements, text, and comments.
  • 83. .append() This method is used to add an element in form of a Node object or a DOMString (basically means text). .appendChild() Similar to the .append method, this method is used to elements in the DOM, but in this case, only accepts a Node object. // Inserting a DOMString const parent = document.createElement('div'); parent.append('Appending Text'); // The div would then look like this <div>Appending Text</div> const parent = document.createElement('div'); parent.appendChild('Appending Text'); // Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
  • 84. </body> <script> // head= document.createElement("h1") // document.body.appendChild(head) // head.innerHTML="Article" const head=document.createElement("h1") const headtext=document.createTextNode("Article") head.appendChild(headtext) document.body.appendChild(head) () </script> Method 1, but not a valid way Method 2,valid way
  • 85. </script> head=document.createElement("div") child=document.createElement("p") t=document.createTextNode("the value of paragraph") child.appendChild(t) head.appendChild(child) document.body.appendChild(head) </script>
  • 86. head=document.createElement("div") child=document.createElement("p") // t=document.createTextNode("the value of paragraph") child.append("this is text inside paragraph") head.appendChild(child) document.body.appendChild(head)
  • 87. body> <ul id="list"> </ul> <button onclick="add()">Add LI item</button> </body> <script> var count=0; function add(){ let liitem= document.createElement("li") litext=document.createTextNode("item"+count) liitem.appendChild(litext) document.getElementById("list").append(liitem) count++ } Adds li item when button Is clicked
  • 89. localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. you can store small amounts of data with localStorage, it’s not suitable for large amounts of data. localStorage is accessible to anyone who uses the device, Both sessionStorage and localStorage maintain a separate storage area for each available origin for the duration of the page session. The main difference between them is that sessionStorage only maintains a storage area. At the same time, the browser is open (including when the page reloads or restores) while localStorage continues to store data after the browser is closed. setItem(): Add key and value to localStorage getItem(): This is how you get items from localStorage removeItem(): Remove an item from localStorage clear(): Clear all data from localStorage key(): Passed a number to retrieve the key of a localStorage
  • 90. <form action="" "> <input type="text" name="text" id="txt"> <input type="email" name="email" id="eml"> <input type="submit" name="" id="sbmit" onclick="str(event)"> </form> <script> let count=0 function str(event){ event.preventDefault(); const username=document.getElementById("txt").value const useremail=document.getElementById("eml").value const data={ name: username, email:useremail } localStorage.setItem(`data${count}`,JSON.stringify(data)) count++; } </script> Set item in local storage
  • 92. Filter array that contains specific pattern keys=Object.keys(localStorage) ['data2', 'data1', 'user', 'data0'] var pattern=/data/ filtered=keys.filter(function(k){ return pattern.test(k)}) ['data2', 'data1', 'data0'] Example of filter method
  • 93. <body onload="show()"> <dl id="userdata"> <dt>Username</dt> <dt>Email</dt> </dl> <script> function show(){ keys=Object.keys(localStorage) let pattern=/data/ const fdata=keys.filter(ptr) function ptr(k) { return pattern.test(k) } console.log(fdata) fdata.forEach(k => { var f=JSON.parse(localStorage.getItem(k)) // let z=f.split(" ") const usr=document.createElement("dd") const eml=document.createElement("dd") usr.append(f.name) eml.append(f.email) document.querySelectorAll("dt")[0].append(usr) document.querySelectorAll("dt")[1].append(eml) }); } </script> To show local storage data in other page Using onload to show data
  • 95.
  • 96. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .article{ background-color: red; color: white; font-family: Georgia, 'Times New Roman', Times, serif; font-size: 2rem; } </style> </head> <body> <ul id="list"> </ul> <button >click</button> </body> </html> { const anchor= document.createElement("a") const li=document.createElement("li") anchor.setAttribute("href","#") li.append("item"+count) anchor.append(li) document.getElementById("list"). append(anchor) count++ for(i=0;i<document.querySelectorAl l("a").length;i++) { document.querySelectorAll("a")[i ].addEventListener("click",rm) function rm() { this.remove() } Code of give task
  • 97. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Social Share</title> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </head> <body> <textarea name="txtn" id="txtid" cols="30" rows="10"></textarea> <button id="twitterShareButton">Share on Twitter</button> <script> document.getElementById('twitterShareButton').addEventListener('click', function() { var tweetText = document.getElementById("txtid").value // The text to be shared on Twitter var twitterShareUrl = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetText) // Open the Twitter share dialog window.open(twitterShareUrl, '_blank', 'width=550,height=420'); }); </script> Twitter share
  • 98. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial- scale=1.0"> <title>Search</title> </head> <body> <input type="search" name="" id="search"> <ul id="list"> <li>computer</li> <li>hardware</li> <li>software</li> <li>css</li> <li>html</li> </ul> </body> </html> <script> document.querySelector("#list").style.display=""//ch ange value to "none" to hide list" document.querySelector("#search").addEventListener(" input",chk) function chk() { searchvalue=document.getElementById("search").value; listarry=document.querySelectorAll("li"); for(i=0;i<listarry.length;i++) { list=listarry[i].textContent if(list.includes(searchvalue)) { document.querySelector("#list").style.di splay='' listarry[i].style.display='' } else{ listarry[i].style.display="none" } } if(searchvalue=='') { document.querySelector("#list").style.display="" //change value to "none" to hide the list after input is deleted } Search text
  • 99. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Game</title> <style> #container{ width: 100%; height: 300px; background-color: black; } #box{ width: 30px; height: 30px; background-color: white; position: relative; left: 1px; top: 1px; transition: left, top; } </style> </head> <body> <div id="container"> <div id="box"></div> </div> </body> </html> <script> let posl=1 let post=1 document.addEventListener("keypress",move) function move(event) { let presskey=event.key presskey=presskey.toLowerCase() let box=document.getElementById("box") if(presskey=="a") { console.log(presskey) box.style.left= posl+"px" posl=posl-10 } else if(presskey=="s") { console.log(presskey) box.style.top=post+"px" post=post+10 } else if(presskey=="d") { console.log(presskey) box.style.left=posl+"px" posl=posl+10; } else if(presskey=="w") Move white box with a,s,d,f keys
  • 101. <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script> <script type = "text/javascript" src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"> /script> head> ody> <li id="btn"><a href="#">Home</a></li> <div id="list"> <p>Course Offered</p> <li>C</li> <li>HTML</li> <li>CSS</li> <li>JAVA</li> <li>JQUERY</li> </div> <input id="txt"> <button value="wa">whatsapp</button> <button value="fb">Facebook</button> <button value="tw">Twitter</button>
  • 102. <style> body{ background-color: cadetblue; } #list{ background-color: lightgrey; width: 25%; position: absolute; display: none; } #list > li{ list-style-type: none; padding: 10px; border: 1px solid red; font-size: .7rem; cursor: pointer; } #list p{ font-size: 1rem; } .submenu { display: none; } .clr{ background-color: black; color: white; } .clsadd{ background-color: tomato; color: white; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; } </style>
  • 103. for(i=0;i<document.querySelectorAll("button").length;i++) { document.querySelectorAll("button")[i].addEventListener("click",function(){ let btn=this.value let share=document.getElementById("txt").value; if (btn=="wa") { let url= 'https://api.whatsapp.com/send?text='+ encodeURIComponent(share) win(url); } if (btn=="tw") { let url= 'https://twitter.com/intent/tweet?text='+ encodeURIComponent(share) win(url); } if(btn=="fb") { // Get the value of the text box // Encode the value for URL var encodedValue = encodeURIComponent(share); // Generate the Facebook share URL with the encoded value var shareURL = `https://www.facebook.com/dialog/feed?app_id=994589648635629&quote${share}` + encodedValue; // Open the Facebook share dialog in a new window window.open(shareURL, '_blank'); } if(btn=="in") { let url= 'https://www.instagram.com/create/story' win(url); } function win(url) { window.open(url,'_blank','width=320px,height=420px') } })
  • 104. https://vercel.com/new For hosting your website https://www.emailjs.com/ Send email using js