Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  163] [ 6]  / answers: 1 / hits: 21043  / 13 Years ago, wed, january 18, 2012, 12:00:00

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);

More From » events

 Answers
38

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.


[#87953] Tuesday, January 17, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
iselauniquef

Total Points: 443
Total Questions: 98
Total Answers: 102

Location: Saint Vincent and the Grenadines
Member since Thu, Oct 15, 2020
4 Years ago
;