Web II (JavaScript) (12)

 Web II (Java Script)

HTML :

The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript.

Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.

DHTML :

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term that combines the features of various web development technologies for creating the web pages dynamic and interactive.

Components of Dynamic HTML

HTML 4.0

CSS

JavaScript

DOM.

HTML 4.0

HTML is a client-side markup language, which is a core component of the DHTML. It defines the structure of a web page with various defined basic elements or tags.

CSS

CSS stands for Cascading Style Sheet, which allows the web users or developers for controlling the style and layout of the HTML elements on the web pages.

JavaScript

JavaScript is a scripting language which is done on a client-side. The various browser supports JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and manipulating the HTML elements. The statements in JavaScript are the commands which tell the browser for performing an action.

DOM

DOM is the document object model. It is a w3c standard, which is a standard interface of programming for HTML. It is mainly used for defining the objects and properties of all elements in HTML.

What is client side scripting?

A client-side script is a small program (or set of instructions) that is embedded (or inserted) into a web page. It is processed within the client browser instead of the web server.

The client side script downloads at the client end from the server along with the HTML web page it is embedded in. The web browser interprets and executes the code and then displays the results on the monitor.

The script that executes on the user’s computer system is called client. It is embedded (or inserted) within the HTML document or can be stored in an external separate file (known as external script).

The script files are sent to the client machine from the web server (or severs) when they are requested. The client’s web browser executes the script, then displays the web page, including any visible output from the script.

What is server side scripting?

A server-side script is a program that is executed on the server side when the user requests information. The script do not download at the client side.

When the client or visitor requests the page, the web server reads it first. After reading, the web server locates the page file on the disk, loads into memory and asks the script engines (or interpreter) to process the script code.

After processing, web server generates the HTML page and pass back to the server. The browser processes the client side script along with the HTML web page from the server and display the web page on the client’s computer screen.

What are the advantages of internet?

1. The Internet gives us access to knowledge, information, and learning opportunities.

2. It connects us to other people in ways that weren’t possible in the past.

3. Supportive communities develop online because of the Internet.

4. The Internet helps us to find where we need to go.

5. We can manage our finances more effectively because of the Internet.

6. The Internet allows us to shop for what we need online.

7. We can create employment opportunities because of the Internet.

8. The Internet provides telecommuting options for employers.

9. Charitable donations are easier to manage because of the Internet.

10. The Internet provides us with plenty of entertainment options.

11. Cloud computing and storage expand our abilities to keep data.

12. The Internet of Things helps us to create a smarter world.

What are the disadvantages of internet?

 What can be used for good can also be used for evil.

1. Pornography and violence are prevalent on the Internet.

2. It creates an addiction to technological devices.

3. People struggle to disconnect from work because of the Internet.

4. The Internet can provide people with your private information.

5. Students can use the Internet to cheat.

6. The Internet exposes all of us to more advertising.

7. Going online can adversely impact a person’s focus and patience.

8. Frequent Internet use can lead to social isolation.

9. Using the Internet often requires a sedentary lifestyle.

10. You might decide to purchase things that you don’t really need.

Difference between Internet and Intranet

The following table compares and contrasts the major differences between Internet and Intranet.

Key

Internet

Intranet

Definition

The Internet is the global system of interconnected computer networks that use the Internet protocol suite to link devices worldwide.

An Intranet is a private network that is contained within an enterprise. It may consist of many interlinked local area networks and also use leased lines in the wide area network.

Users

Internet is the globally connected network, so it can have a huge number of users as compared to the number of users on an Intranet.

Intranet has limited network range, so users on Intranet are also limited and less as compared than that on Internet.

Traffic

The total visitor traffic is exceptionally high due to a large number of users and a public network. It's practically impossible to count.

Because intranets have a small number of users, visitor traffic is limited compared to the Internet. The traffic on an intranet can be counted.

Security

As Internet is exposed to global network and has wider range as compare to that of Intranet, so the possibility of cyber-attacks and other security threats is more in case of Internet.

Intranets, in contrast, are much more secure due to their limited network size.

Type of network

Internet is a type of public network.

Intranet is a type of private network.

Data accessibility

Users can access a huge variety of data on the Internet. Anyone with a network connection can have access to the Internet.

On an Intranet, users can have access to only limited data. Only members of the organization with login credentials can have access to an Intranet.

Scope

The scope of information available on the Internet is vast, encompassing practically every topic, category, and field.

On the other hand, an Intranet contains restricted information about any group or organization, such as the company's databases.

 

What is JavaScript?

JavaScript is a lightweight programming language that web developers commonly use to create more dynamic interactions when developing web pages, applications, servers, and or even games.

Developers generally use JavaScript alongside HTML and CSS The scripting language works well with CSS in formatting HTML elements. However, JavaScript still maintains user interaction, something that CSS cannot do by itself.

JavaScript Advantages

Simple − JavaScript is simple to comprehend and pick up. Both users and developers will find the structure to be straightforward. Additionally, it is very doable to implement, saving web developers a ton of money when creating dynamic content.

Speed − JavaScript is a "interpreted" language, it cuts down on the time needed for compilation in other programming languages like Java. Another client-side script is JavaScript, which accelerates programme execution by eliminating the wait time for server connections.

Interoperability − Because JavaScript seamlessly integrates with other programming languages, many developers favour using it to create a variety of applications. Any webpage or the script of another programming language can contain it.

Server Load − Data validation can be done within the browser itself rather than being forwarded to the server because JavaScript is client-side.

 

JavaScript Disadvantages

Cannot Debug − Although some HTML editors allow for debugging, they are not as effective as editors for C or C++.

Unexpected stop of rendering − The website's entire JavaScript code can stop rendering due to a single error in the code.

Client-side Security − The user can see the JavaScript code; it could be misused by others. Additionally, it is very simple to insert code into the website that impair the security of data transmitted via the website.

Inheritance − JavaScript does not support multiple inheritance; only one inheritance is supported. Browser Support − Depending on the browser, JavaScript is interpreted differently. Therefore, before publication, the code needs to run on various platforms. We also need to check the older browsers because some new functions are not supported by them.

Data types in JavaScript.

Data Types

Description

Example

String

represents textual data

'hello', "hello world!" etc

Number

an integer or a floating-point number

3, 3.234, 3e-2 etc.

Boolean

Any of two values: true or false

true and false

undefined

a data type whose variable is not initialized

let a;

null

denotes a null value

let a = null;

Object

key-value pairs of collection of data

let student = { };

 

How can we add JavaScript into HTML document?

We can JavaScript into HTML document in three ways.

  1. Embedding code
  2. Inline code
  3. External file

I. Embedding code:-

To add the JavaScript code into the HTML pages, we can use the <script>.....</script> tag of the HTML that wrap around JavaScript code inside the HTML program. Users can also define JavaScript code in the <body> tag or <head> tag because it completely depends on the structure of the web page that the users use.

Example

<html>  

<head>  

<title> page title</title>  

</head>  

<body>  

<script>  

document.write("Welcome to Javatpoint");  

</script>  

</body>  

</html> 

II. Inline code:-

Generally, this method is used when we have to call a function in the HTML event attributes. There are many cases (or events) in which we have to add JavaScript code directly eg., OnMover event, OnClick, etc.

Example

<html>  

<head>  

<title> page title</title>  

</head>  

<body>  

<p>  

<a href="#" onClick="alert('Welcome !');">Click Me</a>  

</p>  

<p> in this example we saw how to use inline JavaScript or directly in an HTML tag. </p>  

</body>  

</html>  

III. External file:-

We can also create a separate file to hold the code of JavaScript with the (.js) extension and later incorporate/include it into our HTML document using the src attribute of the <script> tag. It becomes very helpful if we want to use the same code in multiple HTML documents. It also saves us from the task of writing the same code over and over again and makes it easier to maintain web pages.

<html>  

<head>  

<meta charset="utf-8">  

<title>Including a External JavaScript File</title>  

</head>  

<body>  

<form>  

<input type="button" value="Result" onclick="display()"/>  

</form>  

<script src="hello.js">  

</script>  

</body>  

</html>  

Hello.js

function display() {  

alert("Hello World!");  

}  

 

Variable

Local variable and global variable in JS.

Local

·         Any variable that you declare inside a function is said to have Local Scope. You can access a local variable can within a function. If you try to access any variable defined inside a function from outside or another function, it throws an error.

·         Since you cannot access a local variable from outside the function, you can have a variable of the same name in another function as well.

function myFun ()

{

let car_name = “BMW”;                       //Declaring a variable locally

console.log(car_name);

}

myFun();

console.log(car_name); //Accessing the local variable from outside.

Global

·         Any variable declared outside of a function is said to have Global Scope.

·         In simple terms, a variable that can be accessed anywhere in the program is known as a variable with global scope. Globally scoped variables can be defined using any of the three keywords: let, const, and var. 

var scope=”Global”;                             //Global Variable

console.log(scope);                               //Global

function access()

{

console.log(scope);                               //Accessing a global variable

}

access();                                               //Global

.

What is an Operator?

In JavaScript, an operator is a special symbol used to perform operations on operands (values and variables). For example,

2+3;                        //5

Here + is an operator that performs addition, and 2 and 3 are operands.

JavaScript Operator Types

Here is a list of different operators you will learn in this tutorial.

·         Assignment Operators

·         Arithmetic Operators

·         Comparison Operators

·         Logical Operators

·         Bitwise Operators

·         String Operators

·         Other Operators

JavaScript Assignment Operators

Assignment operators are used to assign values to variables. For example,

const x=5;

Here, the = operator is used to assign value 5 to variable x.

Here's a list of commonly used assignment operators:

Operator

Name

Example

=

Assignment operator

a = 7; // 7

+=

Addition assignment

a += 5; // a = a + 5

-=

Subtraction Assignment

a -= 2; // a = a - 2

*=

Multiplication Assignment

a *= 3; // a = a * 3

/=

Division Assignment

a /= 2; // a = a / 2

%=

Remainder Assignment

a %= 2; // a = a % 2

**=

Exponentiation Assignment

a **= 2; // a = a**2

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic calculations. For example,

const number = 3+5; // 8

Here, the + operator is used to add two operands.

Operator

Name

Example

+

Addition

x + y

-

Subtraction

x - y

*

Multiplication

x * y

/

Division

x / y

%

Remainder

x % y

++

Increment (increments by 1)

++x or x++

--

Decrement (decrements by 1)

--x or x--

**

Exponentiation (Power)

x ** y

JavaScript Comparison Operators

Comparison operators compare two values and return a boolean value, either true or false. For example,

Const a=3, b=2;

Console.log(a>b);                                //true

Here, the comparison operator > is used to compare whether a is greater than b.

Operator

Description

Example

==

Equal to: returns true if the operands are equal

x == y

!=

Not equal to: returns true if the operands are not equal

x != y

===

Strict equal to: true if the operands are equal and of the same type

x === y

!==

Strict not equal to: true if the operands are equal but of different type or not equal at all

x !== y

> 

Greater than: true if left operand is greater than the right operand

x > y

>=

Greater than or equal to: true if left operand is greater than or equal to the right operand

x >= y

< 

Less than: true if the left operand is less than the right operand

x < y

<=

Less than or equal to: true if the left operand is less than or equal to the right operand

x <= y

JavaScript Logical Operators

Logical operators perform logical operations and return a boolean value, either true or false. For example,

const x=5, y=3;

(x<6) && (y<5);                  //true

Here, && is the logical operator AND. Since both x < 6 and y < 5 are true, the result is true.

Operator

Description

Example

&&

Logical AND: true if both the operands are true, else returns false

x && y

||

Logical OR: true if either of the operands is true; returns false if both are false

x || y

!

Logical NOT: true if the operand is false and vice-versa.

!x

JavaScript Bitwise Operators

Bitwise operators perform operations on binary representations of numbers.

Operator

Description

&

Bitwise AND

|

Bitwise OR

^

Bitwise XOR

~

Bitwise NOT

<< 

Left shift

>> 

Sign-propagating right shift

>>> 

Zero-fill right shift

JavaScript String Operators

In JavaScript, you can also use the + operator to concatenate (join) two or more strings.

// concatenation operator

console.log('hello' + 'world');

let a = 'JavaScript';

a += ' tutorial';  // a = a + ' tutorial';

console.log(a);

Other JavaScript Operators

Operator

Description

Example

,

evaluates multiple operands and returns the value of the last operand.

let a = (1, 3 , 4); // 4

?:

returns value based on the condition

(5 > 3) ? 'success' : 'error'; // "success"

delete

deletes an object's property, or an element of an array

delete x

typeof

returns a string indicating the data type

typeof 3; // "number"

void

discards the expression's return value

void(x)

in

returns true if the specified property is in the object

prop in object

instanceof

returns true if the specified object is of of the specified object type

object instanceof object_type

 

Functions in JS

What are the advantages of function in JavaScript?

  1. Code reusability: We can call a function several times so it save coding.
  2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task

Write the syntax of function in javascript

function name(parameter1, parameter2, parameter3)

{
  // code to be executed
}

Write an example of Function without parameter/Argument in JavaScript.

function addNumbers()

{

const a = 5;
const b = 10;
const sum = a + b; // 5 + 10

return sum;
}
console.log(addNumbers());

 

Control Structure in JavaScript

Conditionals are control structures that perform different actions depending on the value of an expression.

The if statement allows to make decision and to execute statement conditionally. If the condition evaluates to true, statement is executed, otherwise it is not.

if-else statements:

if(condition)

{

statement1;

                                }

else if(condition)

                                {

                                statement2;

}

else

                                {

                                statement3;

}

Switch Case

The switch statement is similar to the if-else statement. If all of the branches depend on the value of the same expression, the switch control structure can be used instead of the if-else.

When the switch statement is executed, the program attempts to match the value of expression to a case value. If the value of expression is equal to a case value, the program executes the associated statements. If matching is not found, the program looks for the optional default clues. If it is found, associated statements are executed, if not the program skips all statements within the switch statement.

switch(expression)

{

case value1:

statement1;

break;

case value2:

statement2;

break;

default:

statement3;

}

Looping in JavaScript

While

The while loop repeats the execution of the statement as long as expression evaluates to true. It has the following syntax:

while(expression)

{

statement;

}

Before statement in the loop is executed, program tests the value of expression. If the value is false, then the program skips over the statement. Otherwise statement is executed and the value of expression is tested again. It is repeated while the expression is true.
Usually in the while loop there are executed multiple statements through using block statement (statements enclosed in { }).

do-while

The do-while loop is similar to the while loop. The main difference is that first the statement is executed and then expression is checked. It means that statement is always executed at least once.

do

{

statement;

} while(expression);

for

The for loop repeats as long as the condition is met. The syntax is as follows:

for(initialExpression; condition; incrementExpression)

{

statement;

}

First initial expression is executed. Usually a counter variable is initialized here. Then before each iteration the condition is tested. If the value of condition is true statement in the body of the loop is executed. Finally the counter is updated, most frequently incremented.

Function Constructor

The function statement is not the only way to define a new function, you can define your function dynamically using function () constructor along with the new operator.

Example:

<html>

<head>

<script type = "text/JavaScript">

var func = new Function("x", "y", "return x*y;");

function secondFunction()

{

var result;

result = func(10,20);

document.write ( result );

}

</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "secondFunction()" value = "Call Function">

</form>

</body>

</html>

Function Literals:

JavaScript 1.2 introduces the concept of function literals which is another way of defining functions. A function literal is an expression that defines an unnamed function.

Example:

<html>

<head>

<title></title>

<script>

var func = function(x,y)

{

return x*y

};

function secondFunction()

{

var result;

result = func(10,20);

document.write(result);

}

</script>

</head>

<body>

<form>

<input type="button" onClick="secondFunction()" value = "Call Function">

</form>

</body>

</html>

 

JavaScript Events

The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

 

Mouse events:

Event Performed

Event Handler

Description

click

onclick

When mouse click on an element

mouse over

onmouseover

When the cursor of the mouse comes over the element

mouse out

onmouseout

When the cursor of the mouse leaves an element

mouse down

onmousedown

When the mouse button is pressed over the element

mouse up

onmouseup

When the mouse button is released over the element

mouse move

onmousemove

When the mouse movement takes place.

 

Click Event

<html>  

<head> Javascript Events </head>  

<body>  

<script language="Javascript" type="text/Javascript">  

    function clickevent()  

    {  

        document.write("This is JavaTpoint");  

    }  

</script>  

<form>  

<input type="button" onclick="clickevent()" value="Who's this?"/>  

</form>  

</body>  

</html>

MouseOver Event

<html>  

<head>   

<h1> Javascript Events </h1>  

</head>  

<body>  

<script language="Javascript" type="text/Javascript">  

    function mouseoverevent()  

    {  

        alert("This is JavaTpoint");  

    }  

</script>  

<p onmouseover="mouseoverevent()"> Keep cursor over me</p>  

</body>  

</html>  

 

JavaScript Form Validation

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

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.

Re-type Password Validation

<html>

<head>

<script>

function matchpass()

{

var firstpassword=document.f1.password.value;

var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword)

{

return true;

}

else

{

alert("password must be same!");

return false;

}

}

</script>

</head>

<body>

<form name="f1" action="valid.jsp" onsubmit="return matchpass()">

Password:<input type="password" name="password" /><br>

Re-enter Password:<input type="password" name="password2"/><br>

<input type="submit">

</form>

</body>

</html>

 

 

How to validate form in HTML?

Form Validation in HTML

 

<form action = "#" >

Name: <input type = "text" name = "name" required>

<input type = "submit" >

</form>

What data should be validated?

Form validation is needed anytime you accept data from a user. This may include:

1.       Validating the format of fields such as email address, phone number, zip code, name, password.

2.       Validating mandatory fields

3.       Checking the type of data such as string vs number for fields such as social security number.

4.       Ensuring that the value entered is a valid value such as country, date, and so on.

 

Image objects

We can create one image object and read the properties of it. These properties can be manged to move the image across the screen in different directions by using up down left and right buttons.

<html>

<head>

                <title></title>

</head>

<body>

<script type="text/javascript">

                function move(str)

                {

                                var step=50;

                                switch(str)

                                {

                                case "down":

                                                var x=document.getElementById('image').offsetTop;

                                                x=x+step;

                                                document.getElementById('image').style.top=x+'px';

                                                break;

                                case "up":

                                                var x=document.getElementById('image').offsetTop;

                                                x=x-step;

                                                document.getElementById('image').style.top=x+'px';

                                                break;

                                case "left":

                                                var y=document.getElementById('image').offsetLeft;

                                                y=y-step;

                                                document.getElementById('image').style.left=y+'px';

                                                break;

                                case "right":

                                                var y=document.getElementById('image').offsetLeft;

                                                y=y+step;

                                                document.getElementById('image').style.left=y+'px';

                                                break;

                                }

                }

</script>

<img src=eye.png height= 20 id=image style="position: absolute; left: 300px; top: 200px; ">

<input type="button" onclick="move('up')" value="Up"><br>

<input type="button" onclick="move('left')" value="Left">

<input type="button" onclick="move('right')" value="Right"><br>

<input type="button" onclick="move('down')" value="down">

</body>

</html>

 

Form Object

Change the text color through button

<html>

<head>

                <title></title>

</head>

<body>

<h1 id=d_color>plus2net.com</h1>

<button  onclick="change_color('red')">Red</button>

<button  onclick="change_color('yellow')">Yellow</button>

<button  onclick="change_color('Green')">Green</button>

<script>

function change_color(my_color){

 document.getElementById('d_color').style.color=my_color

}

</script>

</body>

</html>

 

<form>

Email : <input type="text" name="email" required>

</form>

HTML Constraint Validation

<html>

<head>

<title></title>

</head>

<body>

<form>

Name : <input type="text" name=" " disabled> <br>

                                  Enter a date before 1980-01-01:

  <input type="date" id="datemax" name="datemax" max="1979-12-31"><br><br>

  Enter a date after 2000-01-01:

  <input type="date" id="datemin" name="datemin" min="2000-01-02"><br><br>

  Enter number  of items (1-5):<input type="number" id="quantity" name="quantity" min="1" max="5">

</form>

</body>

</html>

 

Pattern

       Only letters (either case), numbers, and the underscore; no more than 15 characters.  [A-Za-z0-9_]{1,15}

       Only lowercase letters and numbers; at least 5 characters, but no limit.  [a-zd.]{5,}

       Only letters (either case), numbers, hyphens, underscores, and periods. (Not the slash character, that is being used to escape the period.) The username must start with a letter and must be between 1 and 20 characters long (inclusive).  [a-zA-Z][a-zA-Z0-9-_.]{1,20}  

Constraint Validation DOM Methods

ChekcValidity( )

<html>

<body>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="400">

<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

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

<script>

function myFunction() {

    var inpObj = document.getElementById("id1");

    if (inpObj.checkValidity() == false) {

        document.getElementById("demo").innerHTML = inpObj.validationMessage;

    } else {

        document.getElementById("demo").innerHTML = "Input OK";

    }

}

</script>

 

Comments

Popular posts from this blog

Important Questions for XII

Sample Question Bank Grade 12

Question Collection-11