WT Unit Iii
WT Unit Iii
WT 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);
}
// 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);
}
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
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.
Collections
Document is an object and it contains set of collections.
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.
<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.