Javascript Functions Events and Objects
Javascript Functions Events and Objects
JavaScript Functions
To keep the browser from executing a script when the page loads, you can put your script into a function. A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section.
<script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" /> </form> </body> </html> If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before a user hits the input button. The function displaymessage() will be executed if the input button is clicked. You will learn more about JavaScript events in the JS Events chapter.
Example
<html> <head> <script type="text/javascript"> function product(a,b) { return a*b; } </script> </head> <body> <script type="text/javascript">
JavaScript Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript, there are two different kind of loops:
for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true
Syntax
for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed }
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement.
Example
<html> <body> <script type="text/javascript"> for (i = 1; i <= 6; i++) {
document.write("<h" + i + ">This is heading " + i); document.write("</h" + i + ">"); } </script> </body> </html>
Syntax
while (var<=endvalue) { code to be executed } Note: The <= could be any comparing statement.
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
Example
<html> <body> <script type="text/javascript"> var i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; } </script> </body> </html>
Syntax
do { code to be executed } while (var<=endvalue);
Example
The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:
Example
<html> <body> <script type="text/javascript"> var i=0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i<=5); </script> </body> </html>
Example
<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html>
Example
<html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3) { continue; }
Syntax
for (variable in object) { code to be executed } Note: The code in the body of the for...in loop is executed once for each element/property. Note: The variable argument can be a named variable, an array element, or a property of an object.
Example
Use the for...in statement to loop through an array:
Example
<html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW";
Event Object
The Event object represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons. Events are normally used in combination with functions, and the function will not be executed before the event occurs!
Event Handlers
New to HTML 4.0 was the ability to let HTML events trigger actions in the browser, like starting a JavaScript when a user clicks on an HTML element. Below is a list of the attributes that can be inserted into HTML tags to define event actions. Attribute onabort onblur onchange onclick ondblclick onerror onfocus onkeydown onkeypress onkeyup onload onmousedown onmousemove onmouseout onmouseover The event occurs when... Loading of an image is interrupted An element loses focus The content of a field changes Mouse clicks an object Mouse double-clicks an object An error occurs when loading a document or an image An element gets focus A keyboard key is pressed A keyboard key is pressed or held down A keyboard key is released A page or an image is finished loading A mouse button is pressed The mouse is moved The mouse is moved off an element The mouse is moved over an element
A mouse button is released The reset button is clicked A window or frame is resized Text is selected The submit button is clicked The user exits the page
Some Functions :
(1) ondblclick()
<html> <body> Field1: <input type="text" id="field1" value="Hello World!" /> <br /> Field2: <input type="text" id="field2" /> <br /><br /> Click the button to copy the content of Field1 to Field2.
(2) onfocus()
<html> <head> <script type="text/javascript"> function setStyle(x) { document.getElementById(x).style.background="yellow" } </script> </head> <body> First name: <input type="text" onfocus="setStyle(this.id)" id="fname"> <br /> Last name: <input type="text" onfocus="setStyle(this.id)" id="lname"> </body> </html>
</head> <body> <a href="http://www.w3schools.com" target="_blank"> <img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1" width="26" height="26" onmouseover="mouseOver()" onmouseout="mouseOut()" /></a> </body> </html>
(4) altkey()
<html> <head> <script type="text/javascript"> function isKeyPressed(event) { if (event.altKey==1) { alert("The ALT key was pressed!"); } else { alert("The ALT key was NOT pressed!"); } } </script> </head> <body onmousedown="isKeyPressed(event)"> <p>Click somewhere in the document. An alert box will tell you if you pressed the ALT key or not.</p> </body> </html>
JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:
has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?
Required Fields
The function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. If a value is entered, the function returns true (means that data is OK): function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } }
E-mail Validation
The function below checks if the content has the general syntax of an email. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign: The entire script, with the HTML form could look something like this: <html> <head> <script type="text/javascript">
function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); if (apos<1||dotpos-apos<2) {alert(alerttxt);return false;} else {return true;} } } function validate_form(thisform) { with (thisform) { if (validate_email(email,"Not a valid e-mail address!")==false) {email.focus();return false;} } } </script> </head> <body> <form action="submit.htm" onsubmit="return validate_form(this);" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>
JavaScript Objects
An object is just a special kind of data, with a collection of properties and methods. Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ
from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.
Properties
The syntax for accessing a property of an object is: objName.propName You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows: personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=30; personObj.eyecolor="blue"; document.write(personObj.firstname); The code above will generate the following output: John
Methods
An object can also contain methods. You can call a method with the following syntax: objName.methodName() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the personObj: personObj.sleep();
The following code creates an instance of an object and adds four properties to it: personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj: personObj.eat=eat; 2. Create a template of an object The template defines the structure of an object: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } Notice that the template is just a function. Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand. Once you have the template, you can create new instances of the object, like this: myFather=new person("John","Doe",50,"blue"); myMother=new person("Sally","Rally",48,"green"); You can also add some methods to the person object. This is also done inside the template: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; }
Note that methods are just functions attached to objects. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=new_lastname; } The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").
Create a direct instance of an object <html> <body> <script type="text/javascript"> personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; document.write(personObj.firstname + " is " + personObj.age + " years old."); </script> </body> </html> Create a template for an object <html> <body> <script type="text/javascript"> function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }
myFather=new person("John","Doe",50,"blue"); document.write(myFather.firstname + " is " + myFather.age + " years old."); </script> </body> </html>
link() match() replace() search() slice() small() split() strike() sub() substr() substring() sup() toLowerCase() toUpperCase() toSource() valueOf()
Returns the position of the first occurrence of a specified string value in a string Displays a string in italic Returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string Displays a string as a hyperlink Searches for a specified value in a string Replaces some characters with some other characters in a string Searches a string for a specified value Extracts a part of a string and returns the extracted part in a new string Displays a string in a small font Splits a string into an array of strings Displays a string with a strikethrough Displays a string as subscript Extracts a specified number of characters in a string, from a start index Extracts the characters in a string between two specified indices Displays a string as superscript Displays a string in lowercase letters Displays a string in uppercase letters Represents the source code of an object Returns the primitive value of a String object
Sample Program
<html> <body> <script type="text/javascript"> var txt="Hello World!"; document.write("<p>Big: " + txt.big() + "</p>"); document.write("<p>Small: " + txt.small() + "</p>"); document.write("<p>Bold: " + txt.bold() + "</p>"); document.write("<p>Italic: " + txt.italics() + "</p>"); document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>");
document.write("<p>Fixed: " + txt.fixed() + "</p>"); document.write("<p>Strike: " + txt.strike() + "</p>"); document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>"); document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>"); document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>"); document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>"); document.write("<p>Subscript: " + txt.sub() + "</p>"); document.write("<p>Superscript: " + txt.sup() + "</p>"); document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>"); </script> </body> </html>
getDate()
Returns the day of the month from a Date object (from 131) getDay() Returns the day of the week from a Date object (from 0-6) getFullYear() Returns the year, as a four-digit number, from a Date object getHours() Returns the hour of a Date object (from 0-23) getMilliseconds() Returns the milliseconds of a Date object (from 0-999) getMinutes() Returns the minutes of a Date object (from 0-59) getMonth() Returns the month from a Date object (from 0-11) getSeconds() Returns the seconds of a Date object (from 0-59) getTime() Returns the number of milliseconds since midnight Jan 1, 1970 getTimezoneOffset() Returns the difference in minutes between local time and Greenwich Mean Time (GMT) getUTCDate() Returns the day of the month from a Date object according to universal time (from 1-31) getUTCDay() Returns the day of the week from a Date object according to universal time (from 0-6) getUTCMonth() Returns the month from a Date object according to universal time (from 0-11) getUTCFullYear() Returns the four-digit year from a Date object according to universal time getUTCHours() Returns the hour of a Date object according to universal time (from 0-23) getUTCMinutes() Returns the minutes of a Date object according to universal time (from 0-59) getUTCSeconds() Returns the seconds of a Date object according to universal time (from 0-59) getUTCMilliseconds() Returns the milliseconds of a Date object according to universal time (from 0-999) getYear() Returns the year, as a two-digit or a three/four-digit number, depending on the browser. Use getFullYear() instead !! parse() Takes a date string and returns the number of milliseconds since midnight of January 1, 1970 setDate() Sets the day of the month in a Date object (from 1-31) setFullYear() Sets the year in a Date object (four digits) setHours() Sets the hour in a Date object (from 0-23) setMilliseconds() Sets the milliseconds in a Date object (from 0-999) setMinutes() Set the minutes in a Date object (from 0-59) setMonth() Sets the month in a Date object (from 0-11) setSeconds() Sets the seconds in a Date object (from 0-59) setTime() Calculates a date and time by adding or subtracting a
specified number of milliseconds to/from midnight January 1, 1970 setUTCDate() Sets the day of the month in a Date object according to universal time (from 1-31) setUTCMonth() Sets the month in a Date object according to universal time (from 0-11) setUTCFullYear() Sets the year in a Date object according to universal time (four digits) setUTCHours() Sets the hour in a Date object according to universal time (from 0-23) setUTCMinutes() Set the minutes in a Date object according to universal time (from 0-59) setUTCSeconds() Set the seconds in a Date object according to universal time (from 0-59) setUTCMilliseconds() Sets the milliseconds in a Date object according to universal time (from 0-999) setYear() Sets the year in the Date object (two or four digits). Use setFullYear() instead !! toDateString() Returns the date portion of a Date object in readable form toGMTString() Converts a Date object, according to Greenwich time, to a string. Use toUTCString() instead !! toLocaleDateString() Converts a Date object, according to local time, to a string and returns the date portion toLocaleTimeString() Converts a Date object, according to local time, to a string and returns the time portion toLocaleString() Converts a Date object, according to local time, to a string toSource() Represents the source code of an object toString() Converts a Date object to a string toTimeString() Returns the time portion of a Date object in readable form toUTCString() Converts a Date object, according to universal time, to a string UTC() Takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time valueOf() Returns the primitive value of a Date object
var pi_value=Math.PI; var sqrt_value=Math.sqrt(16); Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it.
Returns the square root of a number Returns the tangent of an angle Represents the source code of an object Returns the primitive value of a Math object
myCars[0] is the first element myCars[1] is the second element myCars[2] is the third element
Sets or returns the number of elements in an array Allows you to add properties and methods to the object
unshift() valueOf()
Adds one or more elements to the beginning of an array and returns the new length Returns the primitive value of an Array object