[go: up one dir, main page]

0% found this document useful (0 votes)
39 views26 pages

CSS Chapter 1 Overall

CSS chapter 1 overall

Uploaded by

sharvari dhokte
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)
39 views26 pages

CSS Chapter 1 Overall

CSS chapter 1 overall

Uploaded by

sharvari dhokte
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/ 26

Unit 1.

Basics of JavaScript Programming


Introduction to JavaScript:
 Brendan Eich is an American computer programmer and technology executive.

 He created the JavaScript programming language and co-founded the Mozilla project, the Mozilla Foundation, and the Mozilla
Corporation.
JavaScript is a programming language for use in HTML pages.
⮚ It was invented in 1995 at Netscape Corporation.
⮚ JavaScript programs are run by an interpreter built into the user's web browser.
⮚ JavaScript can dynamically modify an HTML page.
⮚ A program written in JavaScript can access the elements of a web page, and the browser window in which it is running, and perform
actions on those elements, as well as create new page elements.

1. Features of JavaScript
⮚JavaScript can dynamically modify an HTML page
⮚JavaScript can react to user input
⮚JavaScript can validate user input
⮚JavaScript can be used to create cookies
⮚JavaScript is a full-featured programming language
⮚JavaScript user interaction does not require any communication with the server
⮚ It is supported by almost all browsers
⮚ It supports dynamic typing i.e same variable can be used to hold different values at different times.
⮚ It supports object oriented paradigm and functions.
⮚Supports use of regular expression using which text-pattern matching can be done.
What Can U Do With JavaScript?
⮚Opening new windows with a specified size, position, and style (for example, whether the window has borders, menus, toolbars, and so
on)
⮚Providing user-friendly navigation aids such as drop-down menus
⮚Validation of data entered into a web form to make sure that it is of an acceptable format before the form is submitted to the web server
⮚Changing how page elements look and behave when particular events occur, such as the mouse cursor moving over them
⮚Detecting and exploiting advanced features supported by the particular browser being used, such as third-party plug-ins, or native
support for new technologies
How To Use JavaScript
i. You can include JavaScript statements directly into your HTML code by placing them between <script> and </script> tags
<script type="text/javascript">
... JavaScript statements ...
</script>
ii. You can write the JavaScript code in a separate file with .js extension and include this file in the html file using the src property of
the script tag. This is called as remote javascript
eg. javascriptfile.js
document.write("Hello from javascript File");

hello.html
<html>
<head><script src="javascriptfile.js"></head>
<body>
</body>
</html>
2. Object name, property, method, dot syntax, main event
DOM(document object model)
⮚Each time your browser is asked to load and display a page, it needs to interpret (we usually use the word “parse”) the source
code contained in the HTML file comprising the page.
⮚As part of this parsing process, the browser creates a type of internal model known as a DOM representation based on the
content of the loaded document.
⮚ It is this model that the browser then refers to when rendering the visible page.
⮚You can use JavaScript to access and edit the various parts of the DOM representation, at the same time changing the way the
user sees and interacts with the page in view.

Window And Document Object


⮚Each time your browser loads and displays a page, it creates in memory an internal representation of the page and all its
elements, the DOM.
⮚ In the DOM, elements of your web page have a logical, hierarchical structure, like a tree of interconnected parent and
child objects.
⮚These objects, and their interconnections, form a conceptual model of the web page and the browser that contains and
displays it.
⮚Each object also has a list of properties that describe it, and a number of methods we can use to manipulate those properties
using JavaScript.
⮚Right at the top of the hierarchical tree is the browser window object.

⮚document object contains all of the HTML and other resources that go into making up the displayed page.
⮚ Location object-contains details of the URL of the c urrently loaded page
⮚History object-contains details of the browser‟s previously visited pages
⮚navigator object - stores details of the browser type, version, and capabilities

Object Properties:
1.Object Name: Object is entity. In JavaScript document,window, forms, fields, buttons are some properly used objects.Each object
is identified by ID or name. Array of objects or Array of collections can also becreated.
2. Property: It is the value associated with each object. Each object has its own set ofproperties.
3. Method: It is a function or process associated with each object. Ex: for document object write is a method.
Object Notation: The notation we use to represent objects within the tree uses the dot or period: parent.child
Eg : window.location
This notation can be extended as many times as necessary to represent any object in the tree.
For example : object1.object2.object3 represents object3, whose parent is object2, which is itself a child of object1
The <body> section of your HTML page is represented in the DOM as a child element of the document object; we would access it like
this:
window.document.body
Instead of object the last part can also be a method or property
Eg : window.document.title (here title is a property)
Dot Syntax: It is used to access properties and methods of object.
Main Event: Event causes JavaScript to execute the code. In JavaScript when user submits form, clicks button, writes something to text
box the corresponding event gets triggered and execution of appropriate code is done through Event Handling.

3. Values and variables


Values: It uses six types of values:
• Number: It is numeric value can be integer or float.
• String: It is a collection of characters. Enclosed within single or double quote.
• Boolean: It contains true and false values. Values can be compared with variables and can be used in assignment statement. • Null:
This value can be assigned by reserved word „null‟. It means no value. If we try to access null value error will occur. • Object: It is the
entity that represents some value. Ex: Form is an object on which some components can be placed and used. • Function: It is intended
for execution of some task. There are predefined and user defined functions. The „function‟ keyword is used to define function.
variables:
⮚ JavaScript is case sensitive
⮚ JavaScript has variables that you can declare with the optional var keyword
⮚ Variables declared within a function are local to that function
⮚ Variables declared outside of any function are global variables
⮚ e.g. var name=“kkwagh” ;
⮚ variables are assigned values using = operator
⮚ e.g for integer : var netPrice = 90
for character : var productName = "Leather wallet";
4. Operators and Expressions: primary Expressions
Operators: Following operators are supported:
Sr. Type Operator Meaning Example
No.

1. Arithmetic + Addition or Unary plus c=a+b

- Subtraction or Unary d=-a


minus

* Multiplication c=a*b

/ Division c=a/b

% Mod c=a%b

2. Logical && AND Operator 0&&1

|| OR Operator 0||1
3. Increment ++ Increment by one ++i or i++

4. Decrement -- Decrement by one --i or i--

5. Conditional ?: Conditional Operator a>b?true:false

6. Assignment = Is assigned to a=5

+= Add a value then assign a+=5 (a=a+5)

-= Subtract a value then assign a-=5(a=a-5)

*= Multiply a value then assign a*=5(a=a*5)

/= Divide a value then assign a/=5(a=a/5)

7. Relational < Less than a<4

> Greater than a>4


<= Less than equal to a<=4

>= Greater than equal to a>=4

== Equal to a==4

!= Not Equal to a!=4

=== equal value and equal type a===5

!== not equal value or not equal a!==5


type

8 Special Operators (?:) Conditional Operator returns value


based on the condition. It is like if-
else.

, Comma Operator allows multiple


expressions to be evaluated as
single

statement.
delete Delete Operator deletes a property
from the object.

in In Operator checks if object has


the given property

instanceof checks if the object is an instance


of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a


generator by the generator's iterator

Expressions
An expression is any valid unit of code that resolves to a value.
JavaScript has the following expression categories:
⮚Arithmetic: evaluates to a number, for example 3.14159.
⮚String: evaluates to a character
⮚ Logical: evaluates to true or false.
⮚Primary expressions: Basic keywords and general expressions in JavaScript.
⮚ Left-hand-side expressions: Left values are the destination of an assignment.
Primary Expressions
1) this
- Use the this keyword to refer to the current object. In general, this refers to the calling object in a method.
- It is used either with the dot or the bracket notation:
this['propertyName'] or this.propertyName
2) Grouping Operator
- The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and
division first, then addition and subtraction to evaluate addition first.
var a = 1;
var b = 2;
var c = 3;
a + b * c // 7
a + (b * c) // 7
(a + b) * c // 9
3) Left-hand-side expressions
- Left values are the destination of an assignment.
4) New
- You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types.
var objectName = new objectType([param1, param2, ..., paramN]);
5) super
The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor.
6)Spread operator
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple
elements (for array literals) are expected.
Eg :var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
function f(x, y, z) { }
var args = [0, 1, 2];
f(...args);
5. Object and Array initializers, function Definition expression
- Object and array initializers are expressions whose value is a newly created object or array. These initializer expressions are sometimes
called “object literals” and “array literals.
- An array initializer is a comma-separated list of expressions contained within square brackets. The value of an array initializer is a newly
created array. The elements of this new array are initialized to the values of the comma-separated expressions: [ ] // An empty array: no
expressions inside brackets means no elements
[1+2,3+4] // A 2-element array. First element is 3, second is 7
- The element expressions in an array initializer can themselves be array initializers, which means that these expressions can create nested
arrays:
var matrix = [[1,2,3], [4,5,6], [7,8,9]];
- Undefined elements can be included in an array literal by simply omitting a value between commas. For example, the following array
contains five elements, including three undefined elements:
var sparseArray = [1,,,,5];
- Object initializer expressions are like array initializer expressions, but the square brackets are replaced by curly brackets, and
each subexpression is prefixed with a property name and a colon:
var p = { x:2.3, y:-1.2 }; // An object with 2 properties
var q = { }; // An empty object with no properties
q.x = 2.3;
q.y = -1.2; // Now q has the same properties as p
- Object literals can be nested.
For example:
var rectangle = { upperLeft: { x: 2, y: 2 }, lowerRight: { x: 4, y: 5 } }

6. Property access expressions, invocation expressions


- A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ).
- Functions defined via Functions Expressions can be named or anonymous.

//anonymous function expression


var a = function() {
return 3;
}
//named function expression
var a = function bar() {
return 3;
}
//self invoking function expression
(function sayHello() {
alert("hello!");
})();
- An invocation expression is JavaScript‟s syntax for calling (or executing) a function or method
- It starts with a function expression that identifies the function to be called. The function expression is followed by an open parenthesis, a
comma-separated list of zero or more argument expressions, and a close parenthesis.
- f(0) // f is the function expression; 0 is the argument expression.
Math.max(x,y,z) // Math.max is the function; x, y and z are the arguments.
a.sort() // a.sort is the function; there are no arguments.
7. if statement, if-else, else if ladder, nested if statement, switch statement loop statement- for, while, do while,
continue statement
i. if statement
Syntax:-
if(expression){
//content to be evaluated
}
Example
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
ii. if else statement
Syntax
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
iii. else if ladder
Syntax
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

<script>

var a=20;

if(a==10){

document.write("a is equal to 10");


}

else if(a==15){

document.write("a is equal to 15");

else if(a==20){

document.write("a is equal to 20");

else{

document.write("a is not equal to 10, 15 or 20");

</script>

iv. switch statement


Syntax:-

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}

Ex:
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
v. for loop
Syntax:- for loop
for (initialization; condition; increment)
{
code to be executed
}

Syntax:- for..in loop


for (variable in object) {
// code to be executed
}
<script>

for (i=1; i<=5; i++)


{
document.write(i + "<br/>")
}
</script>
vi. while loop
Syntax:-
while (condition)
{
code to be executed }
Ex:
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
vii. do..while loop
Syntax:-

do{
code to be executed
}while (condition);
<script>

var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
viii. continue statement The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop
var text = ""
var i;
for (i = 0; i < 5; i++) {
if (i === 3) {
continue;
}
text += "The number is " + i + "<br>";
}
ix. break statement: The break statement can also be used to jump out of a loop. The break statement breaks the loop and continues
executing the code after the loop (if any):
Syntax:
jump-statement;
break;
Ex:
for (i = 0; i < 10; i++)
{
if (i === 3)
{ break; }
text += "The number is " + i + "<br>";
}
8. Querying and setting properties
JavaScript Properties
⮚ Properties are the values associated with a JavaScript object.
⮚ A JavaScript object is a collection of unordered properties.
⮚ Properties can usually be changed, added, and deleted, but some are read only
Querying Properties
⮚ The syntax for accessing the property of an object is:
objectName.property // person.age
objectName["property"] // person["age"]
objectName[expression] // x = "age"; person[x]

person.firstname + " is " + person.age + " years old.";


person["firstname"] + " is " + person["age"] + " years old.";
var person = {fname:"John", lname:"Doe", age:25};
for (x in person)
{
txt += person[x];
}
Adding New Properties
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
person.nationality = "English";
9. Deleting properties, property getters and setters

Deleting Properties
⮚ The delete keyword deletes a property from an object
⮚ The delete keyword deletes both the value of the property and the property itself.
⮚ After deletion, the property cannot be used before it is added back again.
⮚ The delete operator is designed to be used on object properties. It has no effect on variables or functions.
⮚The delete operator should not be used on predefined JavaScript object properties. It can crash your application.
Ex: var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];

Getter and Setter Methods


Q. Explain getter and setter properties in Java script with suitable example. (asked in W-19)
Ans: Property getters and setters
1. The accessor properties. They are essentially functions that work on getting and setting a value.
2. Accessor properties are represented by “getter” and “setter” methods. In an object literal they are denoted by get and set.
let obj =
{
get propName()
{
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
3. An object property is a name, a value and a set of attributes. The value may be replaced by one or two methods, known as setter and a
getter.
4. When program queries the value of an accessor property, Javascript invoke getter method(passing no arguments). The retuen value of
this method become the value of the property access expression.
5. When program sets the value of an accessor property. Javascript invoke the setter method, passing the value of right-hand side of
assignment. This method is responsible for setting the property value.
 If property has both getter and a setter method, it is read/write property.
 If property has only a getter method , it is read-only property.
 If property has only a setter method , it is a write-only property.
6. getter works when obj.propName is read, the setter – when it is assigned.
Example:
<head>
<title>Functions</title>
<body>
<script language="Javascript">
var myCar = {
/* Data properties */
defColor: "blue",
defMake: "Toyota",

/* Accessor properties (getters) */


get color() {
return this.defColor;
},
get make() {
return this.defMake;
},

/* Accessor properties (setters) */


set color(newColor) {
this.defColor = newColor;
},
set make(newMake) {
this.defMake = newMake;
}
};
document.write("Car color:" + myCar.color + " Car Make: "+myCar.make)
/* Calling the setter accessor properties */
myCar.color = "red";
myCar.make = "Audi";
/* Checking the new values with the getter accessor properties */
document.write("<p>Car color:" + myCar.color); // red
document.write(" Car Make: "+myCar.make); //Audi
</script>
</head>
</body>
</html>

⮚Getters and setters in JavaScript are used for defining computed properties, or accessors. A computed property is one that uses a
function to get or set an object value.
Example of getter method :
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
}
};
Example of setter method :
var person = {
firstName: "John",
lastName : "Doe",
language : "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang

Q. Explain prompt() and confirm() method of Java script with syntax and example (W-19)
prompt() :
The prompt () method displays a dialog box that prompts the visitor for input.The prompt () method returns the input
value if the user clicks "OK". If the user clicks "cancel" the method returns null. Syntax: window.prompt (text,
defaultText)
Example:
<html>
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" value="click" onclick="msg()"/>
</html>
confirm()
It displays the confirm dialog box. It has message with ok and cancel buttons.
Returns Boolean indicating which button was pressed
Syntax:
window.confirm("sometext");
Example :
<html>
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
</html>

You might also like