Java Reference
In-Depth Information
When the browser calls this function, it will pass an Event object as the e parameter, and you can
retrieve the img element object that received the event by using e.target :
var el = e.target;
You assign this object to a variable called el (short for element), and you use it in the while loop:
while (el.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
}
You also use it to assign its src property in the last line of the function:
el.src = myImages[newImgNumber];
The changes made to changeImg() are minimal, and though it does require just a little bit more code, it
is much more versatile, as you learn later in the chapter.
Using the HTML attribute event handlers is an easy way to connect your JavaScript code to an
element's events, but they have some downsides:
Your HTML and JavaScript are mixed together. This makes it more difficult to maintain and
find and fix bugs.
You can't remove an event handler without changing the HTML.
You can only set up event handlers for elements that appear in your HTML code, as opposed
to elements you create dynamically (like, for example, when you create an element using
document.createElement() ).
These issues, however, are solved with an object's event handler properties.
handling events via object properties
With this method, you first need to define the function that will be executed when the event occurs.
Then you need to set that object's event handler property to the function you defined.
This is illustrated in the following example. Open your editor and type in the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10, Example 3</title>
</head>
<body>
<a id="someLink" href="somepage.html">
Click Me
</a>
<script>
function linkClick() {
 
 
Search WWH ::




Custom Search