JAVASCRIPT

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

JAVASCRIPT

Introduction

JavaScript is a client-side, object-based scripting language that is used to handle


and validate client-side data. JavaScript is also used for making the user interface of
the web pages more dynamic making it responsive to events like the movement of the
mouse, mouse click on a certain HTML element, a button click, etc, using which we
can improve the user experience.

It is an interpreted language which means the script written inside Javascript is


processed line by line and is not compiled before processing. These Scripts are
interpreted by JavaScript interpreter which is a built-in component of the Web
browser.
JavaScript is a lightweight scripting language based on ECMAScript standards. It
executes on the browser and therefore reduces the load on the server.
European Computer Manufacturer's Association(ECMA).
JavaScript, formerly known as LiveScript, has been developed by Netscape and Sun
Microsystems. It is also known as ECMAScript as it was standardized by European
Computer Manufacturer's Association(ECMA). The most recent upgrades were
the ECMAScript6, ES7, ES8, ES9, ES10 and the most
recent ECMAScript2020 which came at the beginning of this year.

Browsers use their own JavaScript Engines to execute the JavaScript code. Some
commonly used browsers are listed below:

1.Chrome uses a V8 engine.


2.Firefox uses the SpiderMonkey engine.
3.Microsoft Edge uses the ChakraCore engine.
4.Safari uses the SquirrelFish engine.
JavaScript Features

1. Light Weight
2. Dynamically Typed
3. Object-Based
4. Functional
5. Platform Independent
6. Prototype-based
7. Interpreted

Advantages of JavaScript

JavaScript has various advantages that make it very useful as a scripting language,
some are listed below:

1. JavaScript makes the webpage more interactive and dynamic.


2. By using JavaScript you can make your webpage to give immediate
feedback to the user so that they would not have to reload the page.
3. You can use JavaScript to perform actions based on how the user
interacts with your webpage using the events generated like a mouse click,
form submit, button click and a lot more.
4. JavaScript can save server traffic by validating the user inputs before
even sending data to the server.
5. JavaScript can be used to store client-side cookies to store data on the
client-side and then read them or delete them.
6. JavaScript can be used to make async HTTP calls to load data from the
server.

Limitations of JavaScript

JavaScript has some limitations too which are listed below:


1. Like Java and other general-purpose programming languages, JavaScript is not
capable to write multi-threading or multiprocessor code.
2. JavaScript can only be used on the client-side i.e. for frontend development.
3. JavaScript is processed in the browser, and if someone disables JavaScript in
their browser, no JavaScript code will be processed. So if you are validating form
values using JavaScript and if any user of your website switches JavaScript off in
his/her browser, then your form validation will stop working.
4. JavaScript opens up a lot of doors and windows for security researchers and
hackers to play around with a webpage.

Include JavaScript in HTML

The JavaScript code can be inserted in HTML file by using the HTML <script> tag.
When an HTML document is loaded with the <script> tag in the web browser, the
browser processes the content enclosed inside the script tag as JavaScript code.

The script tag can contain either scripting statements or refer to an external JavaScript
file. The script tag provides a src attribute that allows us to add a reference to an
external script file.

JavaScript HTML DOM

With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.

The HTML DOM (Document Object Model)

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:

The HTML DOM Tree of Objects


With the object model, JavaScript gets all the power it needs to create dynamic

HTML:

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral


interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."

The W3C DOM standard is separated into 3 different parts:

● Core DOM - standard model for all document types


● XML DOM - standard model for XML documents
● HTML DOM - standard model for HTML documents

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.

Script tag Attributes and its Uses

Following is the basic syntax of using a <script> tag:

<script src="JS_FILE_URL" type="..."></script>

Similarly, we can use the <script> tag to directly add the JavaScript code too, like this:

<script type="text/javascript">

// JS code here

</script>

JavaScript in HTML Webpage

You can use script tag inside an HTML web page to add JavaScript code in the
following ways:

1. In the HEAD element (<head>...</head>)


2. In the BODY element (<body>...</body>)
3. To include an External JavaScript File

Script tag with JavaScript Code in <head> Element

Let's put the script tag inside the HTML head element. The script placed inside
the head element is loaded with the webpage and gets executed if any defined event
occurs.

The code given below shows how to use the <script> tag inside the <head> element of
an HTML document to add some JavaScript code.

<html>

<head>
<title>my first JavaScript</title>

<script>

function text()

document.getElementById("script").innerHTML= "This text has been written


inside the JavaScript.";

</script>

</head>

<body>

<p id="script">this is the old text</p>

<button type="button" onclick=" text() ">click this button to use


JavaScript.</button>

</body>

</html>

Script tag with JavaScript Code in <body> Element

You can place a script tag inside the body element of an HTML document too. The
script tag inside the body element runs when a web page starts loading in a web
browser. Below is the code to show you how to place a <script> element inside
the <body> element of an HTML document:

<html>
<head>

<title>my first JavaScript</title>

</head>

<body>

<script>

function text()

document.getElementById("script").innerHTML= "This text has been written


inside the JavaScript.";

</script>

<p id="script">this is the old text</p>

<button type="button" onclick=" text() ">click this button to use


JavaScript.</button>

</body>

</html>

3. JavaScript Code in an External File

Whenever we put lengthy JavaScript code in an HTML document, it affects the


readability and maintainability of the HTML document. In addition, sometimes there
is a need to use the same JavaScript code in several web pages. In such cases, we can
store the JavaScript code in an external file and save that file with the .js extension.
All JavaScript code files should have an extension .JS and nothing else.

To link the external file, we can provide its location (URL) in the src attribute of the
script tag.

JavaScript Code in External File Example:

The code given below shows you how to link an external JavaScript file with an
HTML document.

<html>

<head>

<title>my first JavaScript</title>

<script src="jsfile.js"></script>

</head>

<body>

<p id="script">this is the old text</p>

<button type="button" onclick="text()">Click this button to use


JavaScript</button>

</body>

</html>

The JavaScript code stored in a file with name jsfile.js

function text()

{
document.getElementById("script").innerHTML = "This text has been
written inside the JavaScript.";

JavaScript Syntax

JavaScript has its own syntax and programming style. Syntax of a language defines
rules of writing the code in that language, what is the correct way and what is not.

1. A semicolon at the end of every statement (is Optional)

Semicolons are used to terminate the JavaScript code statements. A code statement
is a line of code and we can mark the end of each code line by adding a semicolon. In
languages like C, C++, Java, etc. we use a semicolon at the end of each code
statement.

In JavaScript, statements are generally followed by a semicolon(;) which indicates


termination of the statement.

However, it is not necessary to use a semicolon(;) at the end of the statement.

Example

var var_name = value;

Eg:

var a=1;

let a=1;

const a=1;

2. JavaScript White Spaces and Line Breaks


JavaScript interpreter ignores the tabs, spaces, and newlines that appear in the script,
except for strings and regular expressions.

Example

var i = 10;

var j = 20;

var a = i+j; var b = i-j;

3. JavaScript Case Sensitivity

var marks;

var Marks;

var MARKS;

4. JavaScript Comments

It defines two types of comments.

1. Single line Comments


2. Multiline Comments

Let's take an example and understand how we can add these in our JavaScript code.

<html>

<head>

<title>JavaScript Comment Example</title>

<script>

// This is an single line comment and it will not be executed

/*

This is a multiline comment and everything written


inside this block will not be executed.

*/

var x = 10;

var y = 2*x;

</script>

</head>

<body>

<!-- Some HTML code - This is HTML comment -->

</body>

</html>

5. JavaScript Statements

Statements are known as the instructions in any programing language, these


statements are set to be executed by the computer as a computer program.

<html>

<head>

<title>JavaScript Statement</title>

</head>

<body>

<script>

document.write("this is a text") ; // JavaScript statement

var a = 10+20; // Another Statement


document.write(a);

</script>

</body>

</html>

1. JavaScript innerHTML Property

JavaScript lets you write into an HTML element by using innerHTML property. We
can add anything we want, it can be a text message, some HTML element or anything
else.

To do that first you need to provide a specific Id to the HTML element that you
want to access by the JavaScript code.

To access an HTML element JavaScript uses document.getElementById(id) method,


where id is the value of the id attribute of the HTML tag.

Let's take an example, in this example, id attribute is used to identify the HTML
element and innerHTML property is used to set content to it.

<html>

<head>

<title>JavaScript Output using innerHTML</title>

<script>

function addText()

{
document.getElementById("script").innerHTML= "This text has been written using
the JavaScript.";

</script>

</head>

<body>

<p id="script">This is the old text.</p>

<button type="button" onclick="addText()">Click to use JavaScript</button>

</body>

</html>

3. JavaScript Output using document.write()

JavaScript lets you write any output into the HTML webpage by using
the document.write() method. By using this method you can directly write output to
the HTML page.

<html>

<head>

<title>JavaScript Output using document.write()</title>

</head>

<body>

<script>

document.write("This is the text written using JavaScript.") ;


</script>

</body>

</html>

3. JavaScript Output via Alert Box

There are certain websites that give you alert messages when you access them or when
you perform some action you see the output message in alert boxes. You can also
make your webpage to send alert messages to notify something to the user using
JavaScript, to use this feature you need to use the window.alert() method.

4. JavaScript Console Logging<html>

<head>

<title>JavaScript Output using Alert Box</title>

</head>

<body>

<script>

window.alert("This is an alert message.") ;

</script>

</body>

</html>
JavaScript also lets you create console logs which can be seen in the browser's
developers' tools(Console) for debugging purposes. The statement written inside a
console log will be executed but would not be displayed in the browser instead it will
be displayed inside the console of the browser.

The function used for console logging is console.log(SOME-EXPRESSION-OR-


STRING) which can be used to log anything in the browser's console.

To open developer's tools in the Chrome browser, press F12 in Windows

<html>

<head>

<title>JavaScript console example</title>

<script>

console.log(2+3);

</script>

</head>

<body>

<!-- HTML body -->

</body>

</html>

JavaScript Syntax for Declaring a Variable

Following is the syntax for declaring a variable and assigning values to it.

var variable_name;
// or

let variable_name;

// declaring 3 variables together

var x, y, z;

JavaScript Variable Example:

Now let's take a simple example where we will declare a variable and then assign it a
value.

var employeeName; // Declaring a variable

var employeeName = "Rahul"; // Declaring and assigning at the same time

JavaScript HTML DOM Events


HTML DOM allows JavaScript to react to HTML events:
Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an
HTML element.

To execute code when a user clicks on an element, add JavaScript code to an HTML
event attribute:

Examples of HTML events:

● When a user clicks the mouse

● When a web page has loaded

● When an image has been loaded

● When the mouse moves over an element

● When an input field is changed

● When an HTML form is submitted

● When a user strokes a key


Why Use Events
Modern websites have evolved to be interactive and reactive. Instead of presenting
information or functionalities all at once, some can be shown to the user based on a
specific action performed.

Mouse events:

Event Event Description


Performe Handler
d

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an


element

mousedown onmousedown When the mouse button is pressed over the


element

mouseup onmouseup When the mouse button is released over the


element

mousemove onmousemove When the mouse movement takes place.

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an


element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a


form element

change onchange When the user modifies or changes


the value of a form element
Window/Document events
onmouseover and onmouseout

The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element.

<html>
<head>
<script type = "text/javascript">
function over() {
document.write ("Mouse Over");}
function out() {
document.write ("Mouse Out");}
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

Event Event Description


Performed Handler

load onload When the browser finishes the


loading of the page

unload onunload When the visitor leaves the current


webpage, the browser unloads it

resize onresize When the visitor resizes the window


of the browser

onfocus and onblur:

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onfocus and blur Events</h2>

<p>When you enter the input field, a function sets the background color to yellow.</p>
<p>When you leave the input field, a function sets the background color to red.</p>

Enter your name: <input type="text" id="myInput" onfocus="focusFunction()" onblur="blurFunction()">


<script>
function focusFunction() {
document.getElementById("myInput").style.background = "yellow";
}

function blurFunction() {
document.getElementById("myInput").style.background = "red";
}
</script>

</body>
</html>

JavaScript Form Validation

JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.

• Basic Validation

• Data Format Validation

<form action=“demo.html" onsubmit="return check()“>

<label for="">Name</label>

<input type="text" id="name" placeholder="Enter your Name"><br><br>

<label for="">Father Name</label>

<input type="text" id="fname" placeholder="Enter your Name"><br><br>

<label for="">Mother Name</label>

<input type="text" id="mname" placeholder="Enter your Name"><br><br>

<label for="">Mobile</label>

<input type="text" id="mob" placeholder="Enter your Name"><br> <br>

<input type="submit" value="signup">

</form>
<script>
function check(){
name=document.getElementById('name').value;
mob=document.getElementById('mob').value;
if(name==""){
alert("please enter the name");
return false;
}
else if(mob==""){
alert("Please enter mobile number");
return false;
}
}
</script>

Email validation

gmail=/^([a-z0-9])+\@([a-z]{5})+\.([a-z]{3})+$/

if (!gmail.test(em)){

alert("plz enter Valid email ID");

return False;

Mobile number validation

num=/^([0-9]{10})$/

if (!num.test(mob)){

alert("plz enter Valid mobile number");

return False;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy