0% found this document useful (0 votes)
530 views32 pages

Working With Javascript:: Unit - 5

The document provides information on JavaScript objects, properties, and methods for manipulating the window, document, browser, form, and navigator objects. It includes examples of getting window size, finding and modifying HTML elements, and properties of the navigator object for browser detection. Practical tips are given for writing JavaScript code related to arrays, functions, objects, and regular expressions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
530 views32 pages

Working With Javascript:: Unit - 5

The document provides information on JavaScript objects, properties, and methods for manipulating the window, document, browser, form, and navigator objects. It includes examples of getting window size, finding and modifying HTML elements, and properties of the navigator object for browser detection. Practical tips are given for writing JavaScript code related to arrays, functions, objects, and regular expressions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

.

+ UNIT -5

WORKING WITH JAVASCRIPT:

PRATICAL TIPS FOR WRITING SCRIPTS,JAVASCRIPT


OBJECTS:WINDOWS OBJECT –DOCUMENT OBJECT—
BROWSER OBJECT—FORM OBJECT—NAVIGATOR OBJECT
SCREEN

OBJECT—EVENTS,EVENTS HANDLERS,FORMS—
VALIDATIONS,FORM ENHANCEMENTS,JAVASCRIPT
LAIBRARIES.
PRACTICAL TIPS FOR WRITING JAVASCRIPT:

❖ Faster array indexing


❖ Defining functions:
❖ Defining functions in a single line:
❖ Boolean
❖ Filtering Boolean
❖ Creating completely empty objects
❖ Truncating an array
❖ Merging objects
❖ Faster conditional checking
❖ Using regex to replace all characters

JAVASCRIPT OBJECTS:

The Window Object

➢ The window object is supported by all browsers. It


represents the browser's window.All global JavaScript
objects, functions, and variables automatically become
members of the window object Global variables are
properties of the window object.

➢ Global functions are methods of the window object.


Even the document object (of the HTML DOM) is a property
of the window object:
window.document.getElementById("header");

is the same as:


document.getElementById("header");
Window Size:

Two properties can be used to determine the size of the browser


window.

Both properties return the sizes in pixels:

• window.innerHeight - the inner height of the browser


window (in pixels)
• window.innerWidth - the inner width of the browser window
(in pixels)

The browser window (the browser viewport) is NOT including


toolbars and scrollbars.

Example:
let w = window.innerWidth;
let h = window.innerHeight;

PROGRAM:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Window</h2>

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

<script>

document.getElementById("demo").innerHTML =

"Browser inner window width: " + window.innerWidth + "px<br>"


+

"Browser inner window height: " + window.innerHeight + "px";

</script>

</body>

</html>
OUTPUT:

JavaScript Window

Browser inner window width: 668px


Browser inner window height: 502px

Other Window Methods

Some other methods:

• window.open() - open a new window


• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window

The Browser Object Model (BOM):

There are no official standards for the Browser Object Model


(BOM).

Since modern browsers have implemented (almost) the same


methods and properties for JavaScript interactivity, it is often
referred to, as methods and properties of the BOM.

Screen object:
The window.screen object contains information about the user's
screen.

Window Screen:

The window.screen object can be written without the window


prefix.

Properties:

• screen.width
• screen.height
• screen.availWidth
• screen.availHeight
• screen.colorDepth
• screen.pixelDepth

Window Screen Width

The screen.width property returns the width of the visitor's


screen in pixels.

Example

Display the width of the screen in pixels:

document.getElementById("demo").innerHTML ="Screen Width:


+screen.width;

Result will be:

Screen Width: 1366

Window Screen Height

The screen.height property returns the height of the visitor's


screen in pixels.

Example

Display the height of the screen in pixels:

document.getElementById("demo").innerHTML =
"Screen Height: " + screen.height;

Result will be:

Screen Height: 768


Window Screen Available Width:

The screen.availWidth property returns the width of the visitor's


screen, in pixels, minus interface features like the Windows
Taskbar.

Example

Display the available width of the screen in pixels:

document.getElementById("demo").innerHTML =
"Available Screen Width: " + screen.availWidth;

Result will be:

Available Screen Width: 1366

Window Screen Available Height:

The screen.availHeight property returns the height of the visitor's


screen, in pixels, minus interface features like the Windows
Taskbar.

Example:

Display the available height of the screen in pixels:

document.getElementById("demo").innerHTML =
"Available Screen Height: " + screen.availHeight;

Result will be:

Available Screen Height: 728

Window Screen Color Depth:

The screen.colorDepth property returns the number of bits used


to display one color.
All modern computers use 24 bit or 32 bit hardware for color
resolution:

• 24 bits = 16,777,216 different "True Colors"


• 32 bits = 4,294,967,296 different "Deep Colors"

Older computers used 16 bits: 65,536 different "High Colors"


resolution.

Very old computers, and old cell phones used 8 bits: 256
different "VGA colors".

Example

Display the color depth of the screen in bits:

document.getElementById("demo").innerHTML =
"Screen Color Depth: " + screen.colorDepth;

Result will be:

Screen Color Depth: 24

The #rrggbb (rgb) values used in HTML represents "True Colors"


(16,777,216 different colors)

Window Screen Pixel Depth:

The screen.pixelDepth property returns the pixel depth of the


screen.

Example

Display the pixel depth of the screen in bits:

document.getElementById("demo").innerHTML =
"Screen Pixel Depth: " + screen.pixelDepth;
Result will be:

Screen Pixel Depth: 24

Document Object:
The HTML DOM document object is the owner of all other objects
in your web page.

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.

Below are some examples of how you can use the document
object to access and manipulate HTML.

Finding HTML Elements

Method Description

document.getElementById(id) Find an element by


element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class


name
Changing HTML Elements

Property Description

element.innerHTML = new html Change the inner HTML of


content an element

element.attribute = new value Change the attribute value of


an HTML element

element.style.property = new style Change the style of an HTML


element

element.setAttribute(attribute, Change the attribute value of


value) an HTML element
Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output


stream

Form Object:

The Form object represents an HTML <form> element.

Access a Form Object:

You can access a <form> element by using getElementById():

Example
var x = document.getElementById("myForm");
Tip: You can also access a <form> element by using
the forms collection.

Create a Form Object:

You can create a <form> element by using the


document.createElement() method:

Example:
var x = document.createElement("FORM");

Form Object Collections

Collection Description

elements Returns a collection of all elements in a form

Form Object Properties

Property Description

acceptCharset Sets or returns the value of the accept-charset


attribute in a form

action Sets or returns the value of the action attribute in


a form

autocomplete Sets or returns the value of the autocomplete


attribute in a form

encoding Alias of enctype

enctype Sets or returns the value of the enctype attribute


in a form

length Returns the number of elements in a form

method Sets or returns the value of the method attribute


in a form

name Sets or returns the value of the name attribute in


a form

noValidate Sets or returns whether the form-data should be


validated or not, on submission

target Sets or returns the value of the target attribute in


a form
Form Object Methods

Method Description

reset() Resets a form

submit() Submits a form

JavaScript Navigator Object:

The JavaScript navigator object is used for browser detection.


It can be used to get browser information such as appName,
appCodeName, userAgent etc.

The navigator object is the window property, so it can be


accessed by:

1. window.navigator

Or,

1. navigator

Property of JavaScript navigator object

There are many properties of navigator object that returns


information of the browser.
No. Property Description

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise


false
5 userAgent returns the user agent

6 language returns the language. It is supported in


Netscape and Firefox only.

7 userLanguage returns the user language. It is supported


in IE only.

8 plugins returns the plugins. It is supported in


Netscape and Firefox only.

9 systemLanguage returns the system language. It is


supported in IE only.

10 mimeTypes[] returns the array of mime type. It is


supported in Netscape and Firefox only.

11 platform returns the platform e.g. Win32.

12 online returns true if browser is online otherwise


false.
Methods of JavaScript navigator object:

The methods of navigator object are given below.

No. Method Description

1 javaEnabled() checks if java is enabled.

2 taintEnabled() checks if taint is enabled. It is deprecated


since JavaScript 1.2.

Example of navigator object

Let’s see the different usage of history object.

<script>

document.writeln("<br/>navigator.appCodeName:
"+navigator.appCodeName);

document.writeln("<br/>navigator.appName:

"+navigator.appName);

document.writeln("<br/>navigator.appVersion:

"+navigator.appVersion);

document.writeln("<br/>navigator.cookieEnabled:

"+navigator.cookieEnabled);

document.writeln("<br/>navigator.language:

"+navigator.language);
document.writeln("<br/>navigator.userAgent:

"+navigator.userAgent);

document.writeln("<br/>navigator.platform:

"+navigator.platform);

document.writeln("<br/>navigator.onLine: "+navigator.onLine);

</script>

Javascript Form Events

The form property within the document object contains an array


of all forms defined within the document.

Each element within the array is a form object , the index


number associated with the form object defines the order in
which the form appears on the webpage.

The exits a number of events associated with the form element.


The table below enumerates them in detail.

Table : Event handlers for Form Elements.

Object Event Handler

button onClick, onBlur, onFocus

checkbox onClick, onBlur, onFocus.

FileUpLoad onClick, onBlur, onFocus

hidden None

password onBlur, onFocus, onSelect.


Object Event Handler

radio onClick, onBlur, onFocus

reset onReset.

select onFocus, onBlur, onChange.

submit onSubmit

text onClick, onBlur, onFocus , onChange

textarea onClick, onBlur, onFocus , onChange

Javascript Form Events : Buttons

The main utility of a button object is to trigger an event, say


an onClick() event, but a button object has no default action.

The are several types of buttons associated with a form:

• submit
• reset
• button

These events are fired when some click related activity is


registered.

Table : The MouseEvent Object.


Event
Triggered When
Handler

onBlur The form's select, text, or textarea field loses focus.

A select , text ottextarea field has lost the focus and


onChange
values are changed.

onClick An object on a form gets clicked.

onFocus a field gets input focus.

onReset The the form is reset

onSelect text within the textarea field is selected

onSubmit A form is submitted

Javascript Form Events : Using keyword this

The current object is referred using the keyword this, it is used


quite frequently with form element.

For forms with multiple input fields, it get easier to refer them
using this keyword, than by using full name to call the event
handler function.

PROGRAM1:

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<title> JavaScript Handling the Focus Event </title>

</head>

<body>

<script>

function highlightInput(elm){

elm.style.background = "lightgreen";

</script>

<input type="text" onfocus="highlightInput(this)">

<button type="button">Button</button>

</body>

</html>

PROGRAM2:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title> JavaScript Handling the Blur Event </title>

</head>

<body>

<input type="text" onblur="alert('Text input loses focus!')">


<button type="button">Submit</button>

<p><strong>Note:</strong> First click inside the text input


box then click outside to see how it works.</p>

</body>

</html>

PROGRAM 3:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>JavaScript OnChange Event</title>

</head>

<body>

<select onchange="alert('You have changed the selection!');">

<option>Select</option>

<option>OnePlus</option>

<option>Samsung</option>

</select>

<p><strong>Note:</strong> Select any option in select box


to see how it works.</p>

</body>

</html>

OUTPUT:
OnePlus
PROGRAM4:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title> JavaScript OnSubmit Event </title>

</head>

<body>

<form action="../index.php" method="post"


onsubmit="alert('Form data will be submitted to the server!');">

<label>First Name:</label>

<input type="text" name="first-name" required>

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

</form>

</body>

</html>

OUTPUT:

Submit
First Name:

FORM ENHANCEMENTS

The form enhancements is used for create customize web page


with dynamic style,forms,frameworks.

Examples of form enhancement with JavaScript:

• Customizing web pages


• Making web pages more dynamic

• Change type of form input

• Validating forms

• Manipulating cookies

• Interacting with frames

• Calling Java programs

JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message,


and returns false, to prevent the form from being submitted:

JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

HTML Form Example


<form name="myForm" action="/action_page.php" onsubmit="re
turn validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
PROGRAM:

<!DOCTYPE html>

<html>

<head>

<script>

function validateForm() {

let x = document.forms["myForm"]["fname"].value;

if (x == "") {

alert("Name must be filled out");

return false;

</script>

</head>

<body>

<h2>JavaScript Validation</h2>

<form name="myForm" action="/action_page.php"


onsubmit="return validateForm()" method="post">

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

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

</form>

</body>
</html>

OUTPUT:

JavaScript Validation
Submit
Name:

JavaScript Can Validate Numeric Input

JavaScript is often used to validate numeric input:

Please input a number between 1 and 10

Submit

PROGRAM:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

OUTPUT:

JavaScript Validation
Please input a number between 1 and 10:

Submit

Automatic HTML Form Validation

HTML form validation can be performed automatically by the


browser:

If a form field (fname) is empty, the required attribute prevents


this form from being submitted:

HTML Form Example


<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
PROGRAM:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Validation</h2>

<form action="/action_page.php" method="post">

<input type="text" name="fname" required>

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

</form>

<p>If you click submit, without filling out the text field,

your browser will display an error message.</p>

</body>

</html>

OUTPUT:

JavaScript Validation
Submit

If you click submit, without filling out the text field, your browser will display an
error message.

JavaScript Libraries

• JavaScript is arguably the most widely used computer


language in the world.
• The use cases where JavaScript has shown to be replacing
traditional platforms are ever increasing.
Examples

From CDN (jsDelivr):

<scriptsrc="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"><
/script>

From a local path:

<scriptsrc="js/lib/jquery.min.js"></script>
Common libraries

This list showcases JavaScript libraries. They’re sorted


alphabetically. If you don’t see yours, please add it to the list.

Library Type Description

ajile is an open-source browser


module that enables
namespacing, dependency-
ajile Modules
management, and on-demand
loading of cross-domain, local,
and inline scripts.

AngularJS is a tool set for


building the framework most
AngularJS Framework
suited to your application
development

Backbone.js gives structure to


Backbone Framework web applications by providing
models with key-value binding
Library Type Description

and custom events,

Fabric is a powerful graphics


library that makes working with
HTML5 canvas a breeze. It
provides a missing object model
for canvas, as well as an SVG
parser, layer of interactivity,
FabricJS Graphics event system, and a whole suite
of other indispensable tools
(text abstractions, gradients
and patterns, image filters,
flipping, clipping, animation,
free drawing, canvas
serialization, and more).

EaselJS provides straight


forward solutions for working
with rich graphics and
interactivity with HTML5
Canvas. It provides an API that
is familiar to Flash developers,
EaselJS Graphics
but embraces JavaScript
sensibilities. It consists of a full,
hierarchical display list, a core
interaction model, and helper
classes to make working with
Canvas much easier.

Ember is a JavaScript
EmberJS Framework framework for creating
ambitious web applications that
Library Type Description

eliminates boilerplate and


provides a standard application
architecture.

Ext JS is a JavaScript
framework for creating business
application interfaces, it
provides an MVC-style
application architecture, a set of
Ext JS Framework standard UI widgets such as
grids and trees, a theming and
templating system, a charting
and drawing library and other
utilities for creating rich data-
oriented applications.

GLGE is a javascript library


intended to ease the use of
GLGE Graphics WebGL. It’s aim is to mask the
involved nature of WebGL from
the web developer.

jQuery is a fast and concise


JavaScript Library that
simplifies HTML document
traversing, event handling,
Tools and
jQuery animating, and Ajax
Utilites
interactions for rapid web
development. jQuery is designed
to change the way that you
write JavaScript.
Library Type Description

Meteor is a full-stack web


application development
Complete environment. It runs on Node.js
Meteor
Stack and functionalities can be
extended by modules called
Meteorites.

Prototype is a JavaScript
Framework that aims to ease
development of dynamic web
applications. Featuring a
unique, easy-to-use tool kit for
Framework
Prototype class-driven development and
& Utilities
the nicest Ajax library around,
Prototype is quickly becoming
the code base of choice for web
application developers
everywhere.

Raphaël is a small JavaScript


library that should simplify
development work with vector
graphics on the web. If someone
Vector
Raphaël wants to create their own
Graphics
specific chart or image crop and
rotate widget, for example, they
can achieve it simply and easily
with this library.

SproutCore is an open-source
SproutCore Framework JavaScript framework. Its goal
is to allow developers to create
Library Type Description

web applications with advanced


capabilities and a user
experience comparable to that
of desktop applications.

Underscore is a utility-belt
library for JavaScript that
provides a lot of the functional
programming support that you
would expect in Prototype.js (or
Underscore Framework
Ruby), but without extending
any of the built-in JavaScript
objects. It’s the tie to go along
with jQuery’s tux, and
Backbone.js’s suspenders.

YUI is a free, open source


JavaScript and CSS library for
building richly interactive web
JS/CSS
YUI Library applications. The YUI Project is
Framework
a two-way open-source project
managed by the YUI
engineering team at Yahoo!.

You might also like