WT Unit Iii

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

UNIT-III

Arrays
Array is a collection of homogeneous items .
In java script array contains heterogeneous elements .
Syntax : var arrayname=[element1,element2,……….];
Ex : var a=[1,2,3,4];
var colors=[“red”,”blue”,”green”,”yellow”];
var employee=[“raju”,1214,”male”,20000];
Array index starts from 0 .
Array elements are accessed by array name and index of the
element like a[1] , colors[2] etc … .
Array elements are easily accessed by using for in control
structure .
Java Script arrays are dynamic in nature .
Ex : var elements=[1,2,3,4] ; //length =4
elements[4]=5 //length=5
elements[elements.length]=6; //length=6
Array Constructor
 In java Script Array is an Object .
 Java Script provides constructors to create an array .
 There are three versions of array constructors :
1. Array() ;
Ex : var a=new Array();
2.Array(number of Elements);
Ex : var a=new Array(5);
3.Array(comma separated list of Elements);
Ex : var a=new Array(10,20,30);
Multidimensional Arrays :
 Multidimensional Arrays are created by using single dimensional
arrays .
Ex : var a=[ [10,20,30],[20,30,40]];
Passing Parameters to Functions
In JavaScript, primitive types (like numbers
and strings) are passed by value, while
objects (including arrays) are passed by
refere
1. Pass by Value:
For primitive types, a copy of the actual
value is passed to the function.
Changing the parameter inside the function
doesn't affect the original value.
Pass by value:
Example Javascript:
function updateValue(value) {
value = 10;
}

let num = 5;
updateValue(num);
console.log(num); // Output: 5
2. Pass by Reference:
For objects (including arrays), a reference
to the actual object is passed.
Changes made to the object inside the
function are reflected outside.
Example Javascript:

function updateArray(arr) {
arr.push(4);
}

let myArray = [1, 2, 3];


updateArray(myArray);
console.log(myArray);

// Output: [1, 2, 3, 4]
Reference Parameters:
In JavaScript, parameters in a function are passed
by value, but when the value is an object (or an
array), the reference to that object is passed by
value. This means you can modify the object's
properties or elements inside the function.
Example JavaScript:
function updateObject(obj) {
obj.property = 'new value';
}
let myObject = { property: 'old value' };
updateObject(myObject);
console.log(myObject.property);
// Output: 'new value'
Passing Arrays to Functions:
 When you pass an array to a function, you are passing
a reference to the array. Any modifications made to the
array inside the function will affect the original array
outside the function.
Example javascript
function modifyArray(arr) {
arr.push(4);
}

let numbers = [1, 2, 3];


modifyArray(numbers);
console.log(numbers);
// Output: [1, 2, 3, 4]
EVENTS
Event Handling
Event Model
 Event model is used to provide the user interactivity and make the
changes according to the user requirement.

 Events are used to create user friendly web pages.

 We define events in the HTML tags.

Example of events:
1. A mouse Click.
2. A web Page or Image Loading.
3. Mouse over a hot spot on the web page.
4. Selecting an input field in an HTML form.
5. Submitting an HTML Form.
6. A key Stroke.
Event Handling (Contd…)
Input Events:
onsubmit  Event occurs when click on submit button.
onfocus  Event occurs on Focus the elements.
onblur  Event occurs on blur of the mouse.
onchange  Event occurs on drop down value change.
onselect  Event occurs on input text is selected.
onreset  Event occurs on reset button pressed.
onkeydown  Event occurs on pressing down a key.
onkeyup  Event occurs on release a key.
onkeypress  Event occurs on pressing a key.

Click Events:
onclick  Event occurs when the button clicks.
ondblclick  Event occurs on double click.
Event Handling (Contd…)
Mouse Events:
onmouseover  Event occurs on mouse over on text.
onmouseout  Event occurs on mouse out on text.
onmousemove  Event occurs on Mouse move.
onmousedown  Event occurs on Mouse down.
onmouseup  Event occurs on Mouse up.

Load Events:
onload  Event occurs on loading the page or image.
onunload  Event occurs on browser closes the document.
onresize  Event occurs on browser resize.
1.onload:
The onload event occurs when a web page
has finished loading.
It is often used to execute JavaScript code
after all the page content, including images
and stylesheets, has been fully loaded.
Example:

<script>
window.onload = function() {
// Your code to be executed after
the page loads
console.log("Page loaded!");
};
</script>
2.onmouseover and onmouseout:
The onmouseover event is triggered when
the mouse pointer enters an element.
The onmouseout event is triggered when the
mouse pointer leaves an element.
These events are commonly used to create
hover effects.
Example:
<div onmouseover="changeColor(this, 'red')"
onmouseout="changeColor(this,
'blue')">Hover me</div>

<script>
function changeColor(element, color) {
element.style.color = color;
}
</script>
3.onsubmit:
The onsubmit event is triggered when a
form is submitted.
It is commonly used to validate form data
before
<form submission.
onsubmit="return validateForm()">
Example:
<!-- Form fields go here -->
<input type="submit" value="Submit">
</form>

<script>
function validateForm() {
// Your form validation logic
// Return true to submit the form, false to
prevent submission
}
</script>
4.onblur:
The onblur event is triggered when an
element loses focus.
It is often used for input validation or
updating data when a user leaves a form
field.
<input type="text"
Example:
onblur="validateInput(this)">

<script>
function validateInput(input) {
// Your validation logic for the
input value
}
</script>
5.onreset:
The onreset event is triggered when a form
is reset.
It can be used to perform actions or
validations when a user clicks the form's
reset button.
<form onreset="resetForm()">
Example:
<!-- Form fields go here -->
<input type="reset" value="Reset">
</form>

<script>
function resetForm() {
// Your code to reset or clear form
data
}
</script>
6.Onfocus

 The onfocus event is used to detect when an element gains


focus. This event is triggered when an element, such as an
input field or a textarea, becomes the active element,
typically as a result of a user interacting with it (for example,
clicking or tabbing into it). The onfocus event handler is often
used to perform actions or validations when an element gains
focus.

<input type="text" onfocus="handleFocus()">

function handleFocus() {
alert('Input field has
gained focus!');
}
Objects
 Java script has many built in objects which posses the capability of
performing many tasks .
 They are
1. String 2. Math 3.Boolean 4. Date 5.Array 6.Reg_Exp
String
 To manipulate string data java script provides string object and set
of Methods .
 String objects are created by using new String();
Syntax : var str=new String(Hello);
(or)
var str=Hello ;
 length is a property of a string it returns the length of a string .
Methods
1.charAt() : Returns the character at specified index .
2.charCodeAt() : returns the Unicode of the character at the specified
index .
3.concat(): It is used to join to or more strings .it does not change the
existing string ,it returns the copy of the joined string .
4.fromCharCode() : It Converts Unicode values to characters .
5.indexOf(): It returns the First occurrence of a specified value in a
index .
6.lastIndexOf():It returns the position of the last occurrence of a
specified value in index .
7.match():The match method searches for a match between a regular
expression and a string and returns the match.
8.replace() : it replace a matched substring with a new string.
9.search() :it returns the position of the match.
9.slice() :It Extracts a part of a string and returns the extracted part in
a new string.
10.substr(): It extracts the characters from a string with the specified
length of characters .
11.toUpperCase(): It Converts a String to Upper case Letters .
12.toLowerCase():It Converts a String to Lower case Letters .
Math
 It performs Mathematical Operations
 To call methods of Math object by using Math as an
Object.
Methods
1.abs(x) :Returns the absolute value of x.

2.ceil(x) :Returns x ,Rounded upwards to the nearest integer.

3.cos(x) :Gives cosine of x.

4.exp(x) : returns the value of ex .


5.floor(x) : It returns x ,rounded downwards to the nearest integer.

6.log(x) : It return the natural logarithm of x .

7.max(x,y,…….n): Returns the max value from given numbers .

8.min(x,y,……n) :Returns the min value from given numbers .

9.pow(x,y) :Returns the value of xy .

10.random():It returns the random numbers between 0 and 1.

11.round(x) :Returns x to the nearest integer .

12.sin(x):Returns the sin of x .

13.sqrt(x) :Returns the square root of x .

14.tan(x) :Returns the tangent of x .


Date:
The JavaScript date object can be used to get year,
month and day. You can display a timer on the
webpage by the help of JavaScript date object.
 You can use different Date constructors to create
date object. It provides methods to get and set day,
month, year, hour, minute and seconds.
Document Object Model
 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.
 Javascript Document Object Model is used to access
and manipulate all the elements of an HTML
document.
 The DOM is essentially an application programming
interface(API) used for HTML and XML documents, it
represents the document as a hierarchical tree consisting of
nodes.
 With DOM each and every element on document is
accessible using a common set of properties and methods
in Javascript, using which developers can add, remove ,
manipulate individual elements of the page
Dynamic HTML with Java Script
Object Model and Collections
 It possible to create objects for HTML elements to control the
presentation of the web page.
 The object reference should be created for HTML elements by using id
attribute and innerHTML property.

Collections
 Document is an object and it contains set of collections.

 For example all is a collection used to represent all HTML elements in


the document.

Dynamic Styles
 DHTML document object model allows us to change the style of the
object using style attribute.

Ex : document.body.style.backgroundColor=color_name;
Properties of HTML DOM Object
Changing HTML Elements
innerHTML  Returns the Content of id.
nodeName  Name of the node.
nodeValue  Value of Node.
parentNode  Parent node of id.
childNode  Child node of id.
attributes  Attributes of node .
tagName  Name of tag.
setAttribute (attribute , value)  Set the attribute
element.style.property  Set the style of element.
document.createElement()
document.removeChild()
document.appendChild()
document.createTextNode()
document.replaceChild()
Properties of HTML DOM Object (Contd…)
HTML DOM Methods:
getElementById(id)  Get the Element with specified id.
getElementsByTagName(tagname)  Get all elements with a tag name.
getElementsByName(name)  Get all elements with a specified name.

DOM Collection Objects:


Anchors []  Returns an array of all anchors(a) in the document.
All[]  Returns an array of all the HTML Elements in the document.
Forms[] Returns an array of all the forms in the HTML document.
Images[]  Returns an array of all the images in the document.
Links[]  Returns an array of all the links (a and area) in the document.
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:
Accessing field value by document object
Here, document is the root element that
represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of
the input text.
Let's see the simple example of document
object that prints name with welcome message.
In example, we are going to get the value of
input text by user. Here, we are using
document.form1.name.value to get the
value of name field.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value
="print name"/>
</form>
document.getElementById() method:
The document.getElementById() method
returns the element of specified id.
In the previous example , we have used
document.form1.name.value to get the
value of the input value.
Instead of this, we can use
document.getElementById() method to get
value of the input text.
 But we need to define id for the input field.
getElementsByTagName Example
getElementsByTagName: To access elements and
attributes using tag name.
This method will return an array of all the items
with the same tag name.
getElementsByName() method:
The document.getElementsByName()
method returns all the element of specified
name.
The syntax of the getElementsByName()
method is given below:
document.getElementsByName("name") here
name is required.
innerHTML
The innerHTML property can be used to write
the dynamic html on the html document.
It is used mostly in the web pages to generate
the dynamic html such as registration form,
comment form, links etc.

You might also like