Reputation: 9326
I am trying to dynamically change a picture when I click on it, via the addEventListener. I have the pictures in the documents.images array. I already have a function written to switch the images. The problem I am having is binding this in the event that I click on an image.
This is what I tried
document.images[i]src.addEventListener("click", MakeMove, false);
Upvotes: 1
Views: 25547
Reputation: 83356
You want to add the event to the actual image:
document.images[i].addEventListener("click", MakeMove, false);
but older browsers don't support these DOM Level 2 event handlers, so, assuming these images don't have to have multiple click handlers, consider doing
document.images[i].onclick = MakeMove;
EDIT
To pass a parameter to MakeMove
, you'd set onclick
to an anonymous function that calls MakeMove
with whatever values you need:
document.images[i].onclick = function() {
MakeMove(12);
}
From your original code:
document.images[i]src
isn't valid, and
document.images[i].src
would be a string, to which you obviously cannot add an event handler.
Upvotes: 4
Reputation: 2376
It looks like you have a syntax error.
Try:
document.images[i].addEventListener("click", MakeMove, false);
Need to add the event listener directly on the image object. Use JSLint (www.jslint.com) to make sure to avoid this mistakes in the future!
Note: This will only work in browser that support (mostly everything but IE) .addEventListner. It's better probably to use a library so you don't have to worry about this, but if you need, .attachEvent('onclick', MakeMove) will handle IE and other cases.
Upvotes: 1