ES5
ES5
Introduction:
lwhile (no!=Infinity)
l{
lno=no*no;
ldocument.write(no +'<BR>');
l}
</script>
• All of the properties available in number objects are read only .
• Their values remains the same.
• Five properties
• MAX_VALUE: returns the largest possible value in javascript.
• MIN_VALUE: returns the smallest number possible in javascript.
• NEGATIVE_INFINITY: represents largest negative number javascript can handle .
• Represented as –Infinity
• POSSITIVE_INFINITY: represents anything larger than MAX_VALUE and is
represented as infinity.
• NaN: represents a “Not a Number” value.
Number Methods:
• toExponential: Converts a number to Exponential notation.
• toFixed: formats a number with x numbers of digits after a
decimal point.
• toPrecision(x): determines the significant digits to display
—
based on argument passed.
• toString(x): returns the string representation of number’s
—
value.
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var x = 2/0;
• var y = -2/0;
• document.write(x + "<br>");
• document.write(y + "<br>");
• </script></body>
• </html>
toString method()
• <!DOCTYPE html>
• <html>
• <head> <script>
• function f1()
• {
• var num = 15;
• var a = num.toString();
• var b = num.toString(2); //base 2(binay)
• var c = num.toString(8);// base 8(octal)
• var d = num.toString(16);//base 16(hex)
• var n = a + "<br>" + b + "<br>" + c + "<br>" + d;
• var x = document.getElementById("abc");
• x.innerHTML=n;
• }
• </script></head>
• <body> <p id="abc"></p>
• <button onclick="f1()">Try it</button></body></html>
toPrecision() method
• <!DOCTYPE html>
• <html> <head> <script>
• function f1()
• {
• var num = new Number(13.3714);
• var n = num.toPrecision(2);
• var x = document.getElementById("abc");
• x.innerHTML=n
• }
• </script> </head> <body>
• <p id="abc"></p>
• <button onclick="f1()">Click Here</button>
• </body>
• </html>
Math Object
• The Math object allows you to perform mathematical tasks.
• All properties/methods of Math can be called by using Math
as an object, without creating it.
• The Math object includes several mathematical constants
and methods.
• Var pi_val=Math.PI;
• Var y=Math.sin(30);
• Var z= Math.sqrt(25);
Mathematical methods
Method Description
abs() Returns the absolute value of a number
acos() Returns the arccosine (in radians) of a number
asin() Returns the arcsine (in radians) of a number
atan() Returns the arctangent(in radians) of a number
ceil() Returns the smallest integer greater than or equal to a
number
floor() Returns the largest integer less than or equal to a number
pow() Returns base to the exponent power
round() Returns the value of a number rounded to the nearest
integer.
sqrt() Returns the square root of a number
random() Returns random number between 0 and 1.
Examples
12
Click Here
Upper Case and Lower Case
split.
Try It
l a
Try It
String Properties and Methods
• Properties:
• length
• prototype
• constructor
• Methods:
• charAt()
• charCodeAt()
• concat()
• fromCharCode()
• indexOf()
• lastIndexOf()
• localeCompare()
• match()
• replace()
• search()
• slice()
• split()
• substr()
• substring()
• toLowerCase()
• toUpperCase()
• toString()
• trim()
• valueOf()
JavaScript Date Object
• The Date object is used to work with dates and times.
• Date objects are created with the Date() constructor.
• There are four ways of initiating a date:
• new Date() // current date and time
• new Date(milliseconds) //milliseconds since 1970/01/01
• new Date(dateString)
• new Date(year, month, day, hours, minutes, seconds,
milliseconds)
Set Dates
lWe can easily manipulate the date by using the methods available
for the Date object.
lAnd in the following example we set a Date object to be 5 days into
the future:
lvar myDate=new Date();
lmyDate.setDate(myDate.getDate()+5);
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var d=new Date();
• document.write(d);
• </script>
• </body>
• </html>
• Condensed:
• var var1=new Array(“hi”, “hello”, “welcome”);
• Literal:
• var var1=[“hi”, “hello”, “welcome”];
strcat
• <!DOCTYPE html>
• <html>
• <body><p id="demo"></p>
• <button onclick="f1()">Try it</button>
• <script>
• function f1()
• {
• var var1 = ["Jan", "Feb"];
• var var2 = ["Oct", "Nov", "Dec"];
• var var3 = var1.concat(var2);
• var x=document.getElementById("demo");
• x.innerHTML=var3;
• }
• </script></body></html>
Jan,Feb,Oct,Nov,Dec
Try It
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <button onclick="f1()">Try it</button>
• <script>
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• function f1()
• {
• fruits.reverse();
• var x=document.getElementById("demo");
• x.innerHTML=fruits;
• }</script></body></html>
Mango,Apple,Orange,Banana
Try It
• <!DOCTYPE html>
• <html><body>
• <p id="demo">Click the button to sort the array.</p>
• <button onclick=“f1()">Try it</button>
• <script>
• function f1()
• {
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.sort();
• var x=document.getElementById("demo");
• x.innerHTML=fruits;
• }</script></body></html>
Apple,Banana,Mango,Orange
Try It
• <!DOCTYPE html> <html>
• <head><script>
• colors=new
Array("red","orange","green","blue","brown","purple","gray","whit
e");
• Index=0;
• function c1()
• {
• document.bgColor=colors[Index];
• Index=(Index+1)%colors.length;
• }
• function startc()
• {
• setInterval("c1()",3000);
• }
• function stopc()
• {
• window.document.write("Stopped");
• }
• window.onload=startc;
• </script>
• </head>
• <body>
• <form name="f1">
• <input type="button" value="Stop" onclick="stop();">
• </form></body></html>
RegExp
• What is RegExp?
• A regular expression is an object that describes a
pattern of characters.
• When you search in a text, you can use a pattern to
describe what you are searching for.
• A simple pattern can be one single character.
• A more complicated pattern can consist of more
characters, and can be used for parsing,
format checking, substitution and more.
• Regular expressions are used to perform powerful pattern-
matching and "search-and-replace" functions on text.
• Syntax
• var patt=new RegExp(pattern,modifiers);
• var patt=/pattern/modifiers;
• pattern specifies the pattern of an expression
• modifiers specify if a search should be global, case-sensitive,
etc.
• The i modifier is used to perform case-insensitive
matching.
• The g modifier is used to perform a global match (find
all matches rather than stopping after the first
match).
• var str=“Welcome to SE IT”
• var patt=/str/i;
• <!DOCTYPE html>
• <html>
• <head>
• <script>
• function f1()
• {
• var str = "Welcome to SE IT";
• var patt1 = /it/i;
• var result = str.match(patt1);
• document.getElementById("demo").innerHTML=result;
• }
• </script>
• </head>
• <body>
• <p id="demo"></p>
• <input type=”button” onclick="f1()" value=”Click Here”>
• </body>
• </html>
Using test()
the result.
Method: test()
• searches a string for a specified value, and returns true or false,
depending on the result.
• <!DOCTYPE html>
• <html><head></head>
• <body><script>
• var str="Javascript is an intresting scripting language"
• var re=new RegExp("script","g");
• var result=re.test(str);
• document.write("Test 1 value:"+result);
• re= new RegExp("some","g");
• result=re.test(str);
• document.write("Test 2 value:"+result);
• </script>
• </body>
• </html>
• <html>
• <head>
• <noscript>
• <b> Javascript disable</b>
• </noscript>
• <script type="text/javascript">
• var dob = "12-10-1990";
• var ans = dob.split("-");
• alert(ans);
• alert(ans[0]);
• </script>
• </head>
• <body> </body>
• </html>
• <html> <head>
• <script type="text/javascript">
• function calculate()
• {
• var data = document.getElementById("txtdata").value;
• if(data.length==0)
• {
• alert("record missing");
• }
• else
• document.getElementById("result").innerHTML = data;
• }
• </script> </head>
• <body>
• <input type="text" id="txtdata" placeholder="enter record" />
<br />
• <input type="button" value="Enter" onclick="calculate()" />
window.alert("hello javatpoint");
alert("hello javatpoint")
1. Window object
• The window object represents a window in browser.
• An object of window is created automatically by the browser
Method Description
The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.
1.document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
2.document.writeln("<br/>navigator.appName: "+navigator.appName);
3.document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
4.document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
5.document.writeln("<br/>navigator.language: "+navigator.language);
6.document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
7.document.writeln("<br/>navigator.platform: "+navigator.platform);
8.document.writeln("<br/>navigator.onLine: "+navigator.onLine);
navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true
4. Screen Object
• The JavaScript screen object holds information of browser screen.
• It can be used to display screen width, height, colorDepth, pixelDepth
etc.
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.
write("string") writes the given string on the doucment.
writeln("string") writes the given string on the doucment with newline character at the
end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
• <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>
• The document.getElementById() method returns the element of
specified id.
• The document.getElementsByName() method returns all the
element of specified name.
• The document.getElementsByTagName() method returns all the
element of specified tag name.
• <script type="text/javascript">
• function countpara(){
• var totalpara=document.getElementsByTagName("p");
• alert("total p tags are: "+totalpara.length);
• }
• </script>
• <p>This is a pragraph</p>
• <p>count total number of paragraphs</p>
• <p>Another Paragraph</p>
• <button onclick="countpara()">count paragraph</button>
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.
Javascript Events
• The change in the state of an object is known as an Event.
• In html, there are various events which represents that some activity
is performed by the user or by the browser.
• When javascript code is included in HTML, js react over these events
and allow the execution.
• This process of reacting over the events is called Event Handling.
• Thus, js handles the HTML events via Event Handlers.
Mouse Events Keyboard Events
onclick When mouse click on an element onkeydown & When the user press and
onkeyup then release the key
onmouse When the cursor of the mouse comes
over over the element
onmouse When the cursor of the mouse leaves
out an element
onmouse When the mouse button is pressed
down over the element
onmouse When the mouse button is released
up over the element
onmouse When the mouse movement takes
move place.
Form Events Window Events
onfocus When the user focuses on an onload When the browser finishes the loading
element of the page
onsubmit When the user submits the onunloa When the visitor leaves the current
form d webpage, the browser unloads it
onblur When the focus is away from a
form element onresize When the visitor resizes the window of
the browser
onchang When the user modifies or
e changes the value of a form
element
Form Validation
• JavaScript provides a way to validate form's data on the client's computer
before sending it to the web server.
• Form validation generally performs two functions.
• Basic Validation − The form must be checked to make sure all the
mandatory fields are filled in.
• It would require just a loop through each field in the form and check for
data.
• Data Format Validation − Secondly, the data that is entered must be
checked for correct form and value.
• Your code must include appropriate logic to test correctness of data.
• <html> <head> <title>Form Validation</title>
• <script type = "text/javascript">
• <select name = "Country">
• // Form validation code will come here.
• </script> </head> • <option value = "-1"
• <body> selected>[choose yours]</option>
• <form action = "" name = "myForm" onsubmit =
"return(validate());"> • <option value = "1">USA</option>
• <table cellspacing = "2" cellpadding = "2" border = "1"> • <option value = "2">UK</option>
• <tr> <td align = "right">Name</td>
• <td><input type = "text" name = "Name" /></td> • <option value = “3">INDIA</option>
• </tr> • </select> </td> </tr>
• <tr> <td align = "right">EMail</td>
• <td><input type = "text" name = "EMail" /></td>
• <tr>
• </tr> • <td align = "right"></td>
• <tr> <td align = "right">Zip Code</td>
• <td><input type = "text" name = "Zip" /></td>
• <td><input type = "submit"
• </tr>
value = "Submit" /></td>
• <tr> <td align = "right">Country</td> • </tr>
• <td>
•
• </table> </form>
• </body></html>
Data Format Validation
• <script type = "text/javascript">
• function validateEmail() {
• var emailID = document.myForm.EMail.value;
• atpos = emailID.indexOf("@");
• dotpos = emailID.lastIndexOf(".");
•
• if (atpos < 1 || ( dotpos - atpos < 2 )) {
• alert("Please enter correct email ID")
• document.myForm.EMail.focus() ;
• return false;
• }
• return( true );
• }
• </script>
Cookies
• In JavaScript, cookies are piece of data stored in the user's web
browser.
• The cookies are stored in the key-value pair inside the browser.
• We can manipulate the cookies using cookie property of document
object.
• We can set or store a cookie in key-value pair using the cookie
property.
• Web Browsers and Servers use HTTP protocol to communicate.
• HTTP is a stateless protocol. But for a commercial website, it is required to
maintain session information among different pages.
• For example, you have logged in to a particular website on a particular web
page. How do other webpages of the same website know your state that
you have already completed the logged-in process?
• In this case, cookies are used.
• Using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for
better visitor experience or site statistics.
• Your server sends some data to the visitor's browser in the form of a
cookie.
• The browser may accept the cookie.
• It is stored as a plain text record on the visitor's hard drive.
• Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval.
• Once retrieved, your server knows/remembers what was stored
earlier.
• Expires − The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
• Domain − The domain name of your site.
• Path − The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
• Secure − If this field contains the word "secure", then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
• Name=Value − Cookies are set and retrieved in the form of key-value pairs
Setting Cookie:
• JavaScript can manipulate cookies using the cookie property of
the Document object.
• JavaScript can read, create, modify, and delete the cookies that apply
to the current web page.
• document.cookie = "key1 = value1;key2 = value2;expires = date";
Updating a cookie:
• To update the particular key-value pair in the cookie, you can assign
new key-value pair to the document.cookie property.
• document.cookie="key1=value1";
Deleting a cookie
• Sometimes you will want to delete a cookie so that subsequent
attempts to read the cookie return nothing.
• To do this, you just need to set the expiry date to a time in the past