Professional Documents
Culture Documents
Example 1
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
Function parameters are the names listed in the function definition. Function arguments are the real values received by the
function when it is invoked.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function.
When JavaScript reaches a return statement, the function will stop executing. The return value is "returned" back to the "caller":
Example 2
You can reuse code.in JavaScript, functions are objects. JavaScript functions have properties and methods. You can add your own
properties and methods to functions.In JavaScript, functions can be used as variables.JavaScript functions can be redefined like
ordinary variables. It can also be passed as values to other functions.
JavaScript Scope
Scope is the set of variables you have access to. In JavaScript, scope is the set of variables, objects, and functions you have access to.
Example 5
Example 6
var train = " Jan Satabdi";
// code here can use train function myFunction() {
// code here can use train
}
Automatically Global
If you assign a value to a variable that has not been de- clared, it will automatically become a GLOBAL variable.
This code example will declare train as a global variable, even if it is executed inside a function.
Example 7
// code here can use train function myFunction() { train = "Jan Satabdi";
// code here can use train
}
The lifetime of a JavaScript variable starts when it is de- clared. Local variables are deleted when the function is completed. Global
variables are deleted when you close the page.
Function Arguments
In HTML, the global scope is the window object: All global variables belong to the window object.
Example 8
Object-oriented programming
Object-oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses
several techniques including modularity, polymorphism and encapsulation. Today, many popular programming languages
support object- oriented programming (OOP).
In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects.
Terminology Namespace
A container which allows developers to bundle all functionality under a unique, application-specific name.
Class
Defines the characteristics of the object. It is a template definition of variables and methods of an object.
Object
An Instance of a class.
2
Property
Method
Constructor
A method called at the moment of instantiation of an object. It usually has the same name as that of the class containing it.
Inheritance
Encapsulation
A method of bundling the data and methods that use them together.
Abstraction
The conjunction of complex inheritance, methods, properties of an object must be able to simulate a reality model.
Polymorphism
Poly means "many" and morphism means "forms". Different classes might define the same method or property.
In the example below we define a class named Person and we create two instances (person1 and person2).
function Person() { }
var person1 = new Person(); var person2 = new Person();
Please also see Object.create for a new and alternative instantiation method.
The Constructor
The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a
method of the class.
The constructor is used to set the object's properties or to call methods to prepare the object for use.
In the example below, the constructor of the class Person displays an alert when a Person is instantiated.
Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the
prototype property of the class (function) so that inheritance works correctly.
The Methods
Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. To define a
method, assign a function to a named property of the class's prototype property; the name that the function is assigned to is the name
that the method is called by on the object.
In the example below we define and use the method sayHello() for the Person class.
Inheritance
Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The
specialized class is commonly called the child, and the other class is commonly called the parent.
Encapsulation
Encapsulation is by which every class inherits the methods of its parent and only needs to define things it wishes to change.
Abstraction
Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance
(specialization), or composition.
The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model) and the
Function.prototype property is an instance of Object (this demonstrates composition).
Polymorphism
Just like all methods and properties are defined inside the prototype property, different classes can define methods with the same
name; methods are scoped to the class in which they're defined
JavaScript Strings
JavaScript strings are used for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes.You
can use single or double quotes.
Example 1
var cityname = "Chennai"; // Double quotes var cityname = 'Chennai'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string.
Example 2
Example 3
The backslash (\) escape character turns special characters into string characters.
4
Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
The sequence \" inserts a double quote in a string.
Example 4
Example 6
But strings can also be defined as objects with the keyword new.
Example 7
var str = "When I do good I feel good "; var num = str.indexOf("good");
Result:
The lastIndexOf() method returns the index(position) of the last occurrence of a specified text in a string.
Example 8
Example 9
Both methods accept a second parameter as the starting position for the search.
Example 10
Example 11
This example slices out a portion of a string from position 14 to position 21.
Example 12
If a parameter is negative, the position is counted from the end of the string.This example slices out a portion of a string from position -
14 to position -8.
Example 13
If you omit the second parameter, the method will slice out the rest of the string.
Example 14
Example 15
Example 16
Example 17
Example 18
Example 19
Result:
Example 20
Result:
To replace all matches, use a regular expression with a / g flag (global match).
Example 21
Result:
Example 22
The result of str2 will be INFORMATION TECHNOLOGY A string is converted to lower case with toLowerCase().
Example 23
Result:
Example 24
Example 25
India Gate is displayed without leading and trailing blank spaces in alert box.
Example 27
Example 28
Example 29
Result:
Example 30
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
script>
var str = "Temple"; var arr = str.split(""); var text = "";
var i;
for (i = 0; i < arr.length; i++) { text += arr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Result:
8
Te m p l e
Primitive values like 2018 or 1.44 , cannot have properties and methods because they are not objects.
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as
objects when executing methods and properties.
var n = 2018;
n.toString(); // returns 2018 from variable x (2018).toString(); // returns 2018 from literal 2018 (2000+18).toString();
// returns 2018 from expression
2000 + 18
var x = 3. 869;
x.toExponential(2); // returns 3.87e+0 x.toExponential(4); // returns 3.8690e+0 x.toExponential(6); // returns
3.869000e+0
The parameter is optional. If you don't specify it, JavaScript will not round the number.
toFixed() returns a string, with the number written with a specified number of decimals.
Example 34
var x = 3. 869;
x.toFixed(0); // returns 4
x.toFixed(2); // returns 3.87 x.toFixed(4); // returns 3.8690 x.toFixed(6); // returns 3.869000
Example 35
var x = 3. 869;
x.toPrecision(); // returns 3. 869 x.toPrecision(2); // returns 3.9 x.toPrecision(4); // returns 3. 869
x.toPrecision(6); // returns 3. 86900 The valueOf() Method
valueOf() returns a number as a number.
Example 36
var x = 451;
x.valueOf(); // returns 451 from variable x (451).valueOf(); // returns 451 from literal 451
(400 + 51).valueOf(); // returns 451 from expression 400
+ 51
There are 3 JavaScript methods that can be used to convert variables to numbers:he Number() method
1 The parseInt() method
3. The parseFloat() method
These methods are not number methods, but global JavaScript methods.
JavaScript global methods can be used on all JavaScript data types.These are the most relevant methods, when working with numbers.
Method Description
Number() Returns a number, converted from its
argument.
Example 37
Number(true); // returns 1
Number(false); // returns 0
Number("25"); // returns 25
Number(" 25"); // returns 25
Number("25 "); // returns 25
Number(" 25 "); // returns 25 Number("25.77"); // returns 25.77 Number("25,77"); // returns NaN
Number("2577"); // returns NaN
Number("ITI"); // returns NaN
The Number() Method Used on Dates. Number() can also convert a date to a number:
Example 38
Number(new Date("2018-09-15")); // returns 1536969600000
The parseInt()Method
parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.
Example 39
Example 40
Number Properties
Property Description
Result:
Example 43
var n = 2 / 0;
JavaScript NEGATIVE_INFINITY
Example 45
var x = -1 / 0;
JavaScript NaN - Not a Number
Example 47
var x = Number.NaN;
NaN is a JavaScript reserved word indicating that a number is not a legal number.Trying to do arithmetic with a non- numeric string
will result in NaN (Not a Number).
Example 48
Number properties belongs to the JavaScript's number object wrapper called Number.These properties can only be accessed as
Number.MAX_VALUE.
Using newNumber.MAX_VALUE, where 'newNumber' is a variable, expression, or value, will return undefined.
Example 49
var a = 10;
var b = a.MAX_VALUE; // b becomes undefined
The JavaScript Math object allows you to perform mathematical tasks on numbers.
Example 1
Example 2
Example 5
Math.ceil(5.4); // returns 6
Math.floor(x) returns the value of x rounded down to its nearest integer:
Example 6
Math.floor(5.8); // returns 5
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).If you want to use degrees instead of radians,
you have to convert degrees to radians.
Angle in radians = Angle in degrees x PI / 180.
Example 7
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Example 8
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:
Example 9
Example 10
Math.max(20,40,6,0,-10); // returns 40
Example 11
JavaScript provides 8 mathematical constants that can be accessed with the Math object:
Example 12
Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 //
returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of
EMath Constructor
12
Unlike other global objects, the Math object has no constructor. Methods and properties are static. All methods and properties
(constants) can be used without creating a Math object first.
Math Object Methods
Method Description
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
By default, JavaScript will use the browser's time zone and display a date as a full text string.
Date objects are created with the new Date() constructor. There are 4 ways to create a new date object. They are
1 new Date()
2 new Date(year, month, day, hours, minutes, seconds, milliseconds)
3 new Date(date string)
4 new Date(milliseconds)
1 new Date()
new Date() creates a new date object with the current date and time.
Example 1:
new Date(year, month, ...) creates a new date object with a specified date and time.
Example 2
var d = new Date(2018, 06, 30, 09, 10, 25, 0);
7 numbers specify year, month, day, hour, minute, sec- ond, and millisecond (in that order).
Example 3
Example 4
Example 5
Example 7
You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
Example 8
Example 9
3 new Date(dateString)
Example 10
4 new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus milliseconds.
Example 11
Example 12
Example 13
Example 14
Example 17
When a Date object is created, a number of methods al- low you to operate on it. Date methods allow you to get and set the year, month,
day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.
Displaying Dates
By default JavaScript will output dates in full text string format. When you display a date object in HTML, it is automatically converted
to a string, with the toString() method.
Example 15
Example 16
Type Example
ISO Date "2002-06-30" (The International Stan
dard)
Independent of input format, JavaScript will output dates in full text string format.
ISO 8601 is the international standard for the representa- tion of dates and times. The ISO 8601 syntax (YYYY- MM-DD) is also the
preferred JavaScript date format.
ISO dates can be written without specifying the day (YYYY- MM).
Example 19
Result:
Example 20
Result:
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ)
Example 21
Result:
Example 22
Result:
Long dates are most often written with a "MMM DD YYYY" syntax like this.
Example 23
var d = new Date("Aug 31 2012"); Month and day can be in any order.
Example 24
Example 25
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds. Date.parse() returns the number of
16 milliseconds between the date and January 1, 1970.
Example 26
var msec = Date.parse("Sep 15, 1996"); document.getElementById("demo").innerHTML = msec; Result:
842725800000
You can then use the number of milliseconds to convert it to a date object.
Example 27
document.getElementById("demo").innerHTML = d;
Result:
Method Description
The getTime() method returns the number of milliseconds since January 1, 1970.
Example 28
Example 29
Example 30
document.getElementById("demo").innerHTML = d.getMonth();
The getDate() method returns the day of a date as a num- ber (1-31).
Example 32
Example 33
var d = new Date(); alert(d.getHours());
The getMinutes() Method
Example 34
Method Description var d = new Date(); alert(d.getMinutes());
Example 37
In JavaScript, the first day of the week (0) means "Sun- day", even if some countries in the world consider the first day of the week to be
"Monday"
You can use an array of names, and getDay() to return the weekday as a name.
Example 38
var days = ["Sunday", "Monday", "Tuesday", "Wednes- day", "Thursday", "Friday", "Saturday"];
alert(days[d.getDay()]);
UTC date methods are used for working with UTC dates (Universal Time Zone dates).
Set Date methods let you set date values (years, months, days, hours, minutes, seconds, milliseconds) for a Date Object.
<script>
var d = new Date(); d.setDate(18); alert(d);
</script>
Example 43
Example 41
<script>
Example 44
<script>
Example 46
<script>
var d = new Date(); d.setSeconds(20); alert(d);
20
</script>
Example 45
<script>
var d = new Date(); d.setMinutes(15); alert(d);
</script>
Compare Dates
Dates can easily be compared.
The following example compares today's date with Janu- ary 14, 2100.
Example 47
var date1 = new Date(2010, 00, 15); //Year, Month, Date var date2 = new Date(2011, 00, 15); //Year, Month, Date if (date1 > date2)
{
alert("Date One is greather then Date Two.");
}
else
{
alert("Date Two is greather then Date One.");
}
JavaScript HTML DOM
With the HTML DOM, JavaScript can access and modify all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects: The HTML DOM Tree of Objects
With the object model, JavaScript gets all the power it needs to create dynamic HTML
• JavaScript can change all the HTML elements in the page.
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
DOM
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
The HTML DOM is a standard object model and programming interface for HTML. It defines:
HTML DOM methods are actions you can perform (on HTML Elements)
HTML DOM properties are values (of HTML Elements) that you can set or change.
The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.The programming interface is the properties and methods of each object. A
property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like
add or deleting an HTML element).
Example 1
The following example changes the content (the innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Welcome to JavaScript!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
The most common way to access an HTML element is to use the id of the element. In the example above the getElementById method
used id="demo" to find the element.
The easiest way to get the content of an element is by using the innerHTML property. The innerHTML property is useful for getting or
replacing the content of HTML elements.
HTML DOM Document
The document object is the owner of all other objects in your web page. In the HTML DOM object model, the document object
represents your web page. If you want to access objects 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.
Method Description
Method Description
Method Description
Method Description
To do so, you have to find the elements first. There are a couple of ways to do this:
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by HTML object collections
Finding HTML Elements by Id
The easiest way to find HTML elements in the DOM, is by using the element id.
This example finds the element with id="demo":
Example 2
var x = document.getElementById("demo");
If the element is found, the method will return the element as an object (in x).
If the element is not found, x will contain null.
Finding HTML Elements by Tag Name
This example finds the element with id="main", and then finds all <p> elements inside "main":
Example 3
var x = document.getElementById("main"); var y = x.getElementsByTagName("p");
Finding HTML Elements by Class Name
If you want to find all HTML elements with the same class name, use this method get ElementsByClassName()
Example 4
document.getElementsByClassName("intro");
The example above returns a list of all elements with class="intro".
Finding HTML Elements by HTML Object Collections
This example finds the form element with id="frm1", in the forms collection, and displays all element values:
Example 5
var x = document.getElementById("frm1"); var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
The following HTML objects (and object collections) are also accessible:
document.anchors
• document.body
• document.documentElement
• document.embeds
• document.forms
• document.head
• document.images
• document.links
• document.scripts
• document.title
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing the HTML Output Stream
JavaScript can create dynamic HTML content. In JavaScript, document.write() can be used to write directly to the HTML output
stream.
Example 6
<!DOCTYPE html>
<html>
<body>
<script> document.write(Date());
</script>
</body>
</html>
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.To change the content of an
HTML element, use this syntax.
document.getElementById(id).innerHTML = new HTML This example changes the content of a <p> element:
Example 7
<html>
<body>
<p id="p1">Hello World!</p>
<script>
</script>
</body>
</html>
24
Example explained:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">Old Heading</h1>
<script>
var element = document.getElementById("id1"); element.innerHTML = "New Heading";
</script>
</body>
</html>
Example explained:
To change the value of an HTML attribute, use this syntax. document.getElementById(id).attribute = new value
This example changes the value of the src attribute of an
<img> element.
Example 9
<!DOCTYPE html>
<html>
<body>
<img id="Image1" src="flower.gif">
<script>
document.getElementById("Image1").src = "newflower.jpg";
</script>
</body>
</html>
Example explained:
To change the style of an HTML element, use this syntax. document.getElementById(id).style.property = new style The following
example changes the style of a <p> element: Example 10
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "green";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
Using Events
The HTML DOM allows you to execute code when an event occurs. Events are generated by the browser when "things happen" to
HTML elements.
• An element is clicked on
• The page has loaded
• Input fields are changed
This example changes the style of the HTML element with id="id1", when the user clicks a button.
Example 11
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">Heading1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'blue'">
Click Me</button>
</body>
</html>
onclick=JavaScript
In this example, the content of the <h1> element is changed when a user clicks on it.
Example 12
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>
</body>
</html>
Example 13
In the example above, a function named displayDate will be executed when the button is clicked.
</script>
In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
26 function will be executed when the button is clicked.
The
Example 15
Example 16
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over or out of, an HTML element.
The onmousedown, onmouseup and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown
event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed,
the onclick event is triggered.
onload
onfocus
Mouse Events
Change the color of an element when the cursor moves over it.
DOM Event Listener
Example 17
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
</body>
</html>
You can build a website using these popular free and open source website building tools. Nowadays, whether you are an individual
entrepreneur or representing a business organisation, a website is a must for personal and professional growth. Organisations are
spending lots of money to build attractive websites. The following are some of the open source website building tools that you can use to
build your website on your own, without much knowledge about programming or the Internet.
1 WordPress
The official websites for WordPress are https://wordpress.com and https://wordpress.org/.
2 Kompozer
The official website for Kompozer is https://www.kompozer.net.
3 Joomla
The official website for Joomla is https://www.joomla.org/.
4 Drupal
The official website for Drupal is https://www.drupal.org/.
5 OpenCms
28