What is Java Script?JavaScript is an object-based scripting language designed primarily for HTML (Hypertext Markup Language), It supports both IE (internet Explorer) and Netscape Navigator and all other major web browser. Java script can be used for both client side as well as server side in web development. It is not a programming language it can not create executable code while compiling, it is embed in document and while pursing the html document it executes the script, it is an object-based scripting language, while reasonably simple in syntax, construction, and features, the object-based nature of JavaScript still offers programmers significant power and flexibility through the ability to create functions and new objects. 1. What is Java Script2. Java Script Syntax 3. Java Script Objects 4. Java Script Sample Code 5. Java Script FAQ An object in the context of JavaScript, is a collection of properties and methods consisting a set of defined characteristics that you can view and modify, and which you can interact. Methods are the techniques that are used to perform action involving objects and properties. For example statement like Document. Write("Welcome to Javascript") here Document is the object, Write is the method of Document object, JavaScript follows event driven sequence. the events determine the program flow and event handlers determine what happen when these event occurs. Where to Write Java Script You can write javascript in body or head section depend on your r equirement or you can write java script in a sepeate file with extension ".js" and includes it in your HTML document with <SCRIPT SOURCE="abc.js"> tag. 1. Writing text on the browser window <html> <body> <script language="Ja vaScript"> document.write("Hello World!") </script> </body> </html> 2. Writing Formatted Text on the Browser <html> <body> <script language="Java Script"> document.write("<h1>Hello World!</h1>") </script> </body> </html> 3. Using HEAD Section<html> <head> <script language="Ja vaScript"> function message(){ alert("This alert box was called with the onload event") } </script> </head> <body onload="message()"> </body> </html> 4. Using BODY Section <html> <head> </head> <body> <script language="Ja vaScript"> document.write("This message is written when the page loads")
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
What is Java Script? JavaScript is an object-based scripting language designed primarily for HTML(Hypertext Markup Language), It supports both IE (internet Explorer) andNetscape Navigator and all other major web browser. Java script can be usedfor both client side as well as server side in web development. It is not aprogramming language it can not create executable code while compiling, it
is embed in document and while pursing the html document it executes thescript, it is an object-based scripting language, while reasonably simple insyntax, construction, and features, the object-based nature of JavaScript stilloffers programmers significant power and flexibility through the ability tocreate functions and new objects.
1. What is Java Script
2. Java Script Syntax
3. Java Script Objects
4. Java Script Sample Code
5. Java Script FAQ
An object in the context of JavaScript, is a collection of properties and methods consisting a set of definedcharacteristics that you can view and modify, and which you can interact. Methods are the techniques that areused to perform action involving objects and properties. For example statement like Document. Write("Welcome toJavascript") here Document is the object, Write is the method of Document object, JavaScript follows event drivensequence. the events determine the program flow and event handlers determine what happen when these eventoccurs.
Where to Write Java ScriptYou can write javascript in body or head section depend on your requirement or you can write java script in asepeate file with extension ".js" and includes it in your HTML document with <SCRIPT SOURCE="abc.js"> tag.
1. Writing text on the browser window<html><body><script language="JavaScript">document.write("Hello World!")</script></body></html>
2. Writing Formatted Text on the Browser<html><body><script language="Java Script">document.write("<h1>Hello World!</h1>")</script></body></html>
3. Using HEAD Section <html><head><script language="JavaScript">function message(){alert("This alert box was called with the onload event")}</script></head>
<body onload="message()"></body></html>
4. Using BODY Section<html><head></head><body><script language="JavaScript">document.write("This message is written when the page loads")
</script></body></html><!--Example E Using External script --><html><head></head><body><script src="myscript.js"></script><p>The actual script is in an external script file called "myscript.js".</p></body></html>
Java Script Objects
Java Script is object based language, it is not support completley OOPs(Object Oriented Programming) features, you may confuse how you createobject from another object rather than create object from class normally wedo it in any object oriented programming language like C++, Java or dotnet.
Javascript support both built in objects as well as you can create your owncustom objects, there are more than 20 objects, in these section we know in
JavaScript's built in objects from the core of the logical event-driven environ meant within which scripts aredesigned. These objects (frames, windows, documents, forms, and son on) behave in predictable ways and can bemanipulated through their well-defined properties and methods. Built in objects are those that are automaticallyincluded in the java script environment; you don not have to create them or do anything to make them accessibleother refer to them within a script whenever they are nodded.
Sr. Objects Object Description1 Anchor Consist of text string identifying a hypertext link in an HTML document.
2 Button Lets you define and control a push button that appears on an HTML from.
3 Checkbox Lets you exert control over a check box within an HTML form.
4 Date Provides access to date and time functions within a Java Script.
5 Document Consist of properties and methods associated with a specific HTML document file.
6 Element Array Represents a list of individual from elements accessible through an indexed array.
7 Form Consists of the properties and methods associated with individual forms in anHTML document and form objects.
8 Frame Consists of an individual scrollable windows established through <FRAMESET> tagand capable of displaying HTML documents.
9 Hidden Provides access to hidden objects that exits on a form.
10 History Consists of an accessible list of a URL links compiled during the course of a user
navigating through a series of web pages.
11 Link Represents a hypertext link in the form of text or image
12 Location Provides specific data on the currently active URL.
13 Math Performs a wide range of mathematical functions.
14 Navigator Provides version of Navigator
15 Password Provides access to that portion of an HTML form that is used to process text fieldcontaining a password. entered characters are marked as asterisks.
16 Radio Lets you control access to a radio button embedded in an HTML form.
17 Reset Provides access to a reset button appearing on an HTML Form.
18 Select Provides indexed array access to the contents of a selection list or a scrolling listappearing within an HTML form.
19 String Perform string manipulation.
20 Submit Perform processing of submit buttons that have been defined in an HTMLdocument.
21 Text Provides access to text input fields that are used on a HTML form.
22 Textarea Offers processing of scrollable, multiline text blocks that can be embedded withinan HTML form.
23 Window Represents the second highest level objects in the hierarchy.
Java Script Code Sample
There is more than 70 sample JavaScript it includes basic JavaScript syntaxfeatures like variable, creating user define function (UDF) conditionalconstruct, loop, string manipulation, arrays, date objects, math objects,
54. Converts the page into without frames when clicked the button
55. E-Mail Validation
56. Value Validation
57. Length Validation of a text field
58. Form Validation
59. Setting the Focus to the text field
60. Selects the text in the Text Field
61. Radio button
62. Using CheckBox
63. Drop down list
64. Selecting multiple options from a drop down
65. Select Menu
66. Automatically changing tab index
67. Finding the browser of the client
68. All details of browser of the client
69. Monitor Information
70. Redirecting the user to another page
71. Displaying message to the user depending on the browser used by the
client
Example 1. Using Variables in JavaScript Go Top<html><body><script language="JavaScript">var name = "Hege"document.write(name)document.write("<h1>"+name+"</h1>")</script><p>This example declares a variable, assigns a value to it, and then displays the variable.</p>
<p>Then the variable is displayed one more time, only this time as a heading.</p></body></html>
Example 2. Creating Functions in JavaScript Go Top<html><head><script language="JavaScript">function myfunction(){
alert("HELLO")}</script></head><body><form><input type="button" onclick="myfunction()" value="Call function"></form><p>By pressing the button, a function will be called. The function will alert a message.</p></body></html>
Example 3. Function with Arguments Go Top<html><head><script language="JavaScript">function myfunction(txt){alert(txt)}</script></head>
<body><form><input type="button" onclick="myfunction('Hello')" value="Call function"></form><p>By pressing the button, a function with an argument will be called. The function will alert this argument.</p></body></html>
Example 4. Function with two Arguments Go Top<html><head><script language="JavaScript">function myfunction(txt){alert(txt)
}</script></head><body><form><input type="button" onclick="myfunction('Good Morning!')" value="In the Morning"><input type="button" onclick="myfunction('Good Evening!')" value="In the Evening"></form><p>When you click on one of the buttons, a function will be called. The function will alertthe argument that is passed to it.</p></body></html>
Example 5. Function that returns a value Go Top<html><head><script language="JavaScript">function myFunction(){return ("Hello, have a nice day!")}</script></head><body>
<script language="JavaScript">document.write(myFunction())</script><p>The script in the body section calls a function.</p><p>The function returns a text.</p></body></html>
Example 6. Function with arguments that return a value Go Top<html><head><script language="JavaScript">function total(numberA,numberB){return numberA + numberB}</script></head><body><script language="JavaScript">document.write(total(2,3))</script>
<p>The script in the body section calls a function with two arguments, 2 and 3.</p><p>The function returns the sum of these two arguments.</p></body></html>
Example 7. Using If Statement Go Top<html><body><script language="JavaScript">var d = new Date()var time = d.getHours()if (time < 10){document.write("<b>Good morning</b>")}
</script><p>This example demonstrates the If statement.<p>If the time on your browser isless then 10, you will get a "Good morning" greeting.</body></html>
Example 8. IF Else statement in JavaScript Go Top<html><body><script language="JavaScript">var d = new Date()var time = d.getHours()if (time < 10){
document.write("<b>Good morning</b>")}else{document.write("<b>Good day</b>")}</script><p>This example demonstrates the If...Else statement.<p>If the time on your browser isless then 10, you will get a "Good morning" greeting. Otherwise youwill get a "Good day" greeting.
Example 9. Switch Statement Go Top<html><body><script language="JavaScript">var d = new Date()theDay=d.getDay()switch (theDay){case 5:document.write("Finally Friday")breakcase 6:document.write("Super Saturday")breakcase 0:document.write("Sleepy Sunday")breakdefault:document.write("I'm really looking forward to this weekend!")
}</script>
<p>This example demonstrates the switch statement.</p><p>You will receive a different greeting based on what day it is.</p><p>Note that Sunday=0, Monday=1, Tuesday=2, etc.</p></body></html>
Example 10. Using For Loop Go Top
<html><body><script language="JavaScript">for (i = 1; i <= 6; i++)
{document.write("<h" + i + ">This is header " + i)document.write("</h" + i + ">")}</script></body></html>
Example 11. Using While Loop Go Top<html><body><script language="JavaScript">i = 0while (i <= 5){
document.write("The number is " + i)document.write("<br>")i++}</script><p>Explanation:</p><p><b>i</b> equal to 0.</p><p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p><p><b>i</b> will increase by 1 each time the loop runs.</p></body></html>
Example 17. Using substr function with string Go Top<html><body><script language="JavaScript">var str="W3Schools are great"document.write(str.substr(3,6))</script></body></html>
Example 18. Using Arrays in JavaScript Go Top<html><body><script language="JavaScript">
Example 19. Another example of using Arrays in JavaScript Go Top<html><body><script language="JavaScript">var famname = new Array("Jan Egil","Tove","Hege","Stale","Kai Jim","Borge")for (i=0; i<famname.length; i++){document.write(famname[i] + "<br>")}</script></body></html>
Example 20. Using Dates in JavaScript Go Top<html>
<body><script language="JavaScript">var d = new Date()document.write(d.getDate())document.write(".")document.write(d.getMonth() + 1)document.write(".")document.write(d.getFullYear())</script></body></html>
Example 21. Time in JavaScript Go Top<html><body><script language="JavaScript">var d = new Date()document.write(d.getHours())document.write(".")document.write(d.getMinutes())document.write(".")document.write(d.getSeconds())</script></body></html>
Example 22. Setting Date in JavaScript Go Top<html><body><script language="JavaScript">var d = new Date()d.setFullYear("1990")
document.write(d)</script></body></html>
Example 23. Setting Date in UTC Format Go Top<html><body><script language="JavaScript">var d = new Date()document.write(d.getUTCHours())document.write(".")document.write(d.getUTCMinutes())document.write(".")document.write(d.getUTCSeconds())
</script></body></html>
Example 24. Finding weekday of a particular date Go Top<html><body><script language="JavaScript">var d=new Date()var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")document.write("Today is " + weekday[d.getDay()])</script></body></html>
Example 25. Display Full date of the date Go Top<html><body><script language="JavaScript">var d=new Date()var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")document.write(weekday[d.getDay()] + " ")document.write(d.getDate() + ". ")document.write(monthname[d.getMonth()] + " ")
Example 28. Using the random function Go Top<html><body><script language="JavaScript">no=Math.random()*10document.write(Math.round(no))</script></body>
</html>
Example 29. Displaying random number between 1-10 Go Top<html><body><script language="JavaScript">no=Math.random()*10document.write(Math.round(no))</script></body>
</script></head><body><b>Insert a number in either input field, and the number will be converted intoeither Celsius or Fahrenheit.</b><br /><form name="myform"><input name="celsius" onkeyup="convert('C')"> degrees Celsius<br />equals<br /><input name="fahrenheit" onkeyup="convert('F')"> degrees Fahrenheit</form><br />Note that the <b>Math.round</b> method is used,so that the result will be returned as a whole number.</body></html>
Example 33. Converting To Unicode Go Top<html><head><script language="JavaScript">function toUnicode(){var str=document.myForm.myInput.valueif (str!=""){unicode=str.charCodeAt(0)
Example 34. Changing Title of the window Go Top<html><head><script language="JavaScript">function newTitle(){parent.document.title="Put your new title here"
}</script><body>Click this button and check the browser's title field<form><input type="button" onclick="newTitle()" value="Get A new title"></form></body></html>
Example 35. Using Alert Boxes Go Top<html><body><script language="JavaScript">alert("Hello World!")
</script></body></html>
Example 36. Using Alert with line breaks Go Top<html><body><script language="JavaScript">alert("Hello again! This is how we" + '\n' + "add line breaks into an alert box")</script></body></html>
Example 37. Disabling Right Click button of the mouse Go Top<html>
<head><script language="JavaScript">function disable(){if (event.button == 2){alert("Sorry no rightclick on this page.\nNow you can not view my source\nand you can not steal my images")}}</script></head>
<body onmousedown="disable()"><p>Right-click on this page to trigger the event.</p><p>The event property is not recognized in Netscape.</p><p>Note that this is no guarantee that nobody can view the page source, or steal the images.</p></body></html>
Example 38. Using Confirm button Go Top<html><body><script language="JavaScript">var name = confirm("Press a button")if (name == true) {document.write("You pressed OK")}else{document.write("You pressed Cancel")}</script></body></html>
<!-- Example 39 Using Prompt function--><html><head></head><body><script language="JavaScript">var name = prompt("Please enter your name","")if (name != null && name != ""){document.write("Hello " + name)}</script></body></html>
Example 39. Opening a new window Go Top<html><head><script language=javascript>function openwindow(){window.open("http://www.w3schools.com")}</script></head><body><form><input type=button value="Open Window" onclick="openwindow()"></form></body></html>
Example 40. Opening a full size window Go Top<html><head><script language=javascript>function openwindow(){w_height=screen.availheightw_width=screen.availwidthwindow.open("default.asp","","height=" + w_height + ",width=" + w_width + ",left=0,top=0")
Example 41. Specifying window position Go Top<html><head><script language="JavaScript">function openwindow(){window.open("http://www.w3schools.com","my_new_window","width=400,height=400,top=0,left=0")}</script></head><body><form><input type="button" value="Open Window" onclick="openwindow()">
</form></body></html>
Example 42. Closing the window Go Top<html><head><script language=javascript>function openwindow(){mywindow=window.open("http://www.w3schools.com","My_new_window","width=300,height=300")}function closewindow(){mywindow.close()}
Example 44. Button which displays source of the web page Go Top<html><head><script language="JavaScript">function source(){location="view-source:" + window.location.href }</script></head><body><form><input type="button" value="View source" onclick="source()"></form></body></html>
Example 45. Mark a bookmark on the web page Go Top<html><head>
<script language="JavaScript">function bookmark(){window.external.AddFavorite("http://www.w3schools.com","W3Schools.com")}</script></head><body><form><input type="button" onclick="bookmark()" value="Click here to bookmark me"></form></body></html>
Example 46. Setting the homepage Go Top<html>
<head><script language="JavaScript">function makeDefault(element){element.style.behavior='url(#default#homepage)';element.setHomePage('http://www.w3schools.com');}</script></head><body><p>Click the button and W3Schools will become your default home page.</p><form><input type="button"onclick="makeDefault(this)"value="Make W3Schools your default homepage"></form>
</body></html>
Example 47. Refreshing the screen on clicking the button Go Top<html><head><script language="JavaScript">function refresh(){location.reload()}
Example 48. Status Bar message Go Top<HTML><HEAD><TITLE>JavaScript Example</TITLE><SCRIPT LANGUAGE="JavaScript">function scrollit_r21(seed){var msg=" Yes...you can say whatever you want here...Just go on and on forever!"var out = " ";var c = 1;if (seed > 100) {seed--;var cmd="scrollit_r21(" + seed + ") ";
Example 49. Last modified page Go Top<html><body>This page was last modify:<br /><script language="JavaScript">document.write(document.lastModified)</script><br /><br />
Example 54. Converts the page into without frames when clicked the button Go Top<html><head><script language="JavaScript">function breakout(){
if (window.top != window.self){window.top.location="tryjs_breakout.htm"}}</script></head><body><form>To break out of the frame:<input type="button" onclick="breakout()" value="Click me">
Example 55. E-Mail Validation Go Top<html><head><script language="JavaScript">function validate(){x=document.myFormat=x.myEmail.value.indexOf("@")if (at == -1){alert("Not a valid e-mail")return false}}</script></head><body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter your E-mail address:<input type="text" name="myEmail"><input type="submit" value="Send input"></form></body></html>
Example 56. Value Validation Go Top<html><head><script language="JavaScript">function validate(){x=document.myFormtxt=x.myInput.value
if (txt>=1 && txt<=5){return true}else{alert("Must be between 1 and 5")return false}}</script></head><body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">Enter a value from 1 to 5:<input type="text" name="myInput">
{x=document.myForminput=x.myInput.valueif (input.length>5){alert("Do not insert more than 5 characters")return false}else{return true}}</script></head><body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">In this input box you are not allowed to insert more than 5 characters:<input type="text" name="myInput"><input type="submit" value="Send input"></form></body></html>
Example 58. Form Validation Go Top<html><head><script language="JavaScript">function validate(){x=document.myFormat=x.myEmail.value.indexOf("@")code=x.myCode.valuefirstname=x.myName.valuesubmitOK="True"if (at==-1){alert("Not a valid e-mail")
submitOK="False"}if (code<1 || code>5){alert("Your code must be between 1 and 5")submitOK="False"}if (firstname.length>10){alert("Your name must be less than 10 letters")submitOK="False"}if (submitOK=="False"){return false}
}</script></head><body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">Enter your e-mail:<input type="text" name="myEmail"><br> Enter your code, value from 1 to 5:<input type="text" name="myCode"><br> Enter your first name, max 10 letters:<input type="text" name="myName">
Example 59. Setting the Focus to the text field Go Top<html><head><script language="JavaScript">function setfocus(){document.forms[0].field.focus()}</script></head><body><form><input type="text" name="field" size="30"><input type="button" value="Get Focus" onclick="setfocus()"></form></body></html>
Example 60. Selects the text in the Text Field Go Top<html><head><script language="JavaScript">function setfocus(){document.forms[0].field.select()document.forms[0].field.focus()}</script></head><body><form><input type="text" name="field" size="30" value="input text">
Example 61. Radio button Go Top<html><head><script language="JavaScript">function check(browser){document.forms[0].answer.value=browser}</script></head>
<body><form>Which browser is your favorite<br><input type="radio" name="browser" onclick="check(this.value)"value="Explorer">Microsoft Internet Explorer<br><input type="radio" name="browser" onclick="check(this.value)"value="Netscape">Netscape Navigator<br><input type="text" name="answer"></form></body></html>
Example 62. Using CheckBox Go Top<html><head><script language="JavaScript">function check(){coffee=document.forms[0].coffeeanswer=document.forms[0].answertxt=""for (i = 0; i<coffee.length; ++ i){if (coffee[i].checked){txt=txt + coffee[i].value + " "}}answer.value=txt}</script></head><body>
<form>How do you like your coffee<br><input type="checkbox" name="coffee" value="cream">With cream<br><input type="checkbox" name="coffee" value="sugar">With sugar<br><input type="text" name="answer"><input type="button" name="test" onclick="check()" value="Order"></form></body></html>
Example 63. Drop down list Go Top<html><head><script language="JavaScript">function put()
{option=document.forms[0].dropdown.options[document.forms[0].dropdown.selectedIndex].texttxt=optiondocument.forms[0].favorite.value=txt}</script></head><body><form><p>Select your favorite browser:<select name="dropdown" onchange="put()"><option>Internet Explorer<option>Netscape Navigator</select></p>
}</script></head><body><p>This script automatically sets focus to the next input fieldwhen the current input field's maxlength has been reached</p><form name="myForm"><input size="3" tabindex="1" name="myInput"maxlength="3" onkeyup="toUnicode(this,this.value)"><input size="3" tabindex="2" name="mySecond" maxlength="3" onkeyup="toUnicode(this,this.value)"><input size="3" tabindex="3" name="myThird" maxlength="3" onkeyup="toUnicode(this,this.value)"></form></body></html>
Example 67. Finding the browser of the client Go Top<html><head><script language="JavaScript">document.write("You are browsing this site with: "+ navigator.appName)</script></head>
<body></body></html>
Example 68. All details of browser of the client Go Top<html><body><script language="JavaScript">document.write("BROWSER: ")document.write(navigator.appName + "<br>")document.write("BROWSERVERSION: ")document.write(navigator.appVersion + "<br>")document.write("CODE: ")document.write(navigator.appCodeName + "<br>")document.write("PLATFORM: ")
Example 71. Displaying message to the user depending on the browser used by the client <html><head><script language="JavaScript">function browserversion(){txt="Your Browser is unknown"browser=navigator.appVersionif (browser.indexOf("2.")>-1){txt="Your Browser is from the stone-age"}
if (browser.indexOf("3.")>-1){txt="You should update your Browser."}if (browser.indexOf("4.")>-1){txt="Your Browser is good enough"}document.forms[0].message.value=txt}</script></head><body onload="browserversion()"><form><input type="text" name="message" size="50"></form>