Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Java Scripts - Merged

JavaScript is an object-oriented scripting language used to build dynamic and interactive effects into web pages. It is lightweight, cross-platform, and embedded directly into HTML. JavaScript code is translated by the browser JavaScript engine and run client-side without needing to connect to a server. Common uses of JavaScript include dynamically changing HTML content, validating form inputs, and handling user interactions and events.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Scripts - Merged

JavaScript is an object-oriented scripting language used to build dynamic and interactive effects into web pages. It is lightweight, cross-platform, and embedded directly into HTML. JavaScript code is translated by the browser JavaScript engine and run client-side without needing to connect to a server. Common uses of JavaScript include dynamically changing HTML content, validating form inputs, and handling user interactions and events.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Java scripts

 JavaScript is an object-based scripting language which is lightweight and cross-platform.


 JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web browser.

What is JavaScript

 JavaScript (js) is a light-weight object-oriented programming language which is used by several


websites for scripting the webpages. It is an interpreted, full-fledged programming language
that enables dynamic interactivity on websites when applied to an HTML document.

 Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their
scripting and query language.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured
programming language.
3. JavaScript is an object-oriented programming language that uses prototypes rather than using classes
for inheritance.
4. It is a light-weighted and interpreted language.
5. It is a case-sensitive language.
6. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
7. It provides good control to the users over the web browsers.

Client-side scripting
 Client-side scripting is when the server sends the code along with the HTML web page to the client.
The script is referred to by the code.
 In other words, client-side scripting is a method for browsers to run scripts without having to connect
to a server.
 The code runs on the client’s computer’s browser either while the web page is loading or after it has
finished loading.
 Client-side scripting is mostly used for dynamic user interface components including pull-down menus,
navigation tools, animation buttons, and data validation.
 It is currently quickly expanding and evolving on a daily basis. As a result, creating client-side web
programming has become easier and faster, lowering server demand.
 By far the most popular client-side scripting languages or web scripting languages, JavaScript and
jQuery are frequently utilized to construct dynamic and responsive webpages and websites.
 The browser downloads the code to the local machine (temporarily) and begins processing it without
the server. As a result, client-side scripting is browser-specific.
Simple java script example

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().

The example above "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to
"Hello JavaScript":

JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript :

1. local variable
2. global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

JavaScript local variable


A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:

1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>

A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with
window object is known as global variable. For example:

1. <script>
2. var value=50;//global variable
3. function a(){
4. alert(value);
5. }
6. function b(){
7. alert(value);
8. }
9. </script>

JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Example

Calculate the product of two numbers, and return the result:

// Function is called, the return value will end up in x


let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

Conditional Statements
Conditional statements are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

Example

Make a "Good day" greeting if the hour is less than 18:00:

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example

If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example

If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a
"Good day" greeting, otherwise a "Good evening":
The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.

Example

The getDay() method returns the weekday as a number between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

This example uses the weekday number to calculate the weekday name:
JavaScript Loops
 The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.
 Loops can execute a block of code a number of times.

Different Kinds of Loops


JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

The For Loop


The for statement creates a loop with 3 optional expressions:

for (expression 1; expression 2; expression 3) {


// code block to be executed
}

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

The For In Loop


The JavaScript for in statement loops through the properties of an Object:

Syntax
for (key in object) {
// code block to be executed
}
Example

The While Loop


The while loop loops through a block of code as long as a specified condition is true.

Syntax
while (condition) {
// code block to be executed
}

Example

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is
less than 10:

The Do While Loop


The do while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);
Example

The example below uses a do while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:

JavaScript Objects
 A javaScript object is an entity having state and behavior (properties and method). For example: car, pen,
bike, chair, glass, keyboard, monitor etc.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct
create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).


2) By creating instance of Object
The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be assigned in the current object by
using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.


DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page. The

Document Object Model (DOM) is an application programming interface (API)


for HTML and XML documents. It defines the logical structure of documents
and the way a document is accessed and manipulated.

A Document object represents the HTML document that is displayed in


that window. The way a document content is accessed and modified is called
the Document Object Model, or DOM. The Objects are organized in a
hierarchy. This hierarchical structure applies to the organization of objects in a
Web document.

• Window object − Top of the hierarchy. It is the outmost element of the


object hierarchy.

• Document object − Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the
page.

• Form object − Everything enclosed in the <form>...</form> tags sets the


form object.

• Form control elements − The form object contains all the elements
defined for that object such as text fields, buttons, radio buttons, and
checkboxes.
The HTML DOM model is constructed as a tree of Objects. So it is a tree structure.

With the object model, JavaScript gets all the power it needs to create dynamic
HTML: It can perform the following operations :

• Change All the HTML elements in the page


• HTML attributes in the page
• all the CSS styles in the page
• remove existing HTML elements and attributes
• add new HTML elements and attributes
• react to all existing HTML events in the page
• can create new HTML events in the page

DOM Definition

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

2. 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."

Document Object

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It


is the root element that represents the html document. It has properties and
methods. By the help of document object, we can add dynamic content to our web
page.

As mentioned earlier, it is the object of window. So


1. window.document

Is same as
1. document

Properties of document object

We can have various properties of the document as mentioned below.


Methods of document object

We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the document.

writeln("string") writes the given string on the document with newline


character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

Components

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

1. 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

Types of DOM

There are several DOMs in existence.

• The Legacy DOM − This is the model which was introduced in early
versions of JavaScript language. It is well supported by all browsers, but
allows access only to certain key portions of documents, such as forms,
form elements, and images.

• The W3C DOM − This document object model allows access and
modification of all document content and is standardized by the World
Wide Web Consortium (W3C). This model is supported by almost all the
modern browsers.
• The IE4 DOM − This document object model was introduced in Version
4 of Microsoft's Internet Explorer browser. IE 5 and later versions include
support for most basic W3C DOM features

JavaScript Form Validation

It is important to validate the form submitted by the user because it may contain
inappropriate values. So, validation is must to authenticate user.

Importance

JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer JavaScript
form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.

Example

In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the
next page until given values are correct.

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validatefor
m()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

You might also like