6.4  Java Script - Events and Functions

Index Code Tester

OBJECTIVE

DISCUSSION

Events


Functions 

function myFunction() {
   alert("hi from myfunction")
}        

function mySecondFunction() {
   myFunction()  //can call a function in a function
}
<div id = "myDiv" onclick = "myFunction()">hi</div>  


Sample Code   

<html>
<head>
<script>
   function myFunction() {
      alert("Hi from myFunction")
   }
   function mySecondFunction() {
      myFunction()
   }
</script>
</head>

<body>
<div id = "myID" onclick = "mySecondFunction()">Hi</div>
</body>
</html>  

EXERCISES

1.  Copy and paste the above code into Notepad and save as an .htm document.

  1. Test the page. 
  2. Set the width of the <div> to "50" and the background color to "red".
  3. Add an event so that the alert is displayed when the user moves the mouse over the <div>. 
  4. Add a function called changeDiv().  In the function, add code that sets the innerText of the <div> equal to the value from a prompt.
  5. Call the function from the "onclick" event of the button.

2.  Create a page with two textboxes and a button.  When the user clicks the button, the contents of the textboxes should be added together and displayed.  You can choose any method you want for displaying the result.  Are the textboxes added as numbers or strings?  Note: If you want to add the textboxes as numbers you must use the built-in parseFloat() function.

3.  Modify your page in exercise 1 so that the <div> changes colors when the user moves the mouse over it and then returns to the original color when the mouse is moved off of it.

4.  Create a page with an image on it.  When the user moves the mouse over the image it should change to another image and when they move the mouse off of the image it should return to its original image.

5. Find an online reference that lists events for objects.  Add a link to this reference on your web site.

LINKS AND HELP

http://www.w3schools.com/js/js_intro.asp
http://www.webteacher.com/javascript/
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/