Jump to content

Javascript Question: I'm Calling A Function From A Few Different Images Using Onclick="", How Can I Have The Script Get The Calling Image's Source?


Asfastasdark

Recommended Posts

OK, here's what I'm trying to do, I realize the title is hard to understand.html file:

<img src="img1.gif" onclick="function1()" /><img src="img2.gif" onclick="function1()" />

external .js file:

function function1() {//nothing here yet; this is where I have a problem}

What I'm trying to do here is the following: find a way for function1() to get the image source of the image calling it. For example, if the img1.gif image called function1(), how could I get function1() to go, "Well, I'm being called by the first image, so it's source must be img1.gif"? It would be good if there was something like document.callingelement.src... but I don't think there is. Can anyone help?

Link to comment
Share on other sites

<img src="img1.gif" onclick="function1(this.src)" />function function1(src) {alert(src);}
Could I do:<img src="img1.gif" onclick="function1()" />function function1() {alert(this.src);}?Wouldn't that work with other images as well? Or am I doing something wrong there?
Link to comment
Share on other sites

You need to send something to the function, either the entire image element or just the src. You can do this:<img src="img1.gif" onclick="function1(this)" />function function1(img) {alert(img.src);}or this:<img src="img1.gif" onclick="function1(this.src)" />function function1(src) {alert(src);}Inside the function this does not refer to the image, it typically refers to the window object.

Link to comment
Share on other sites

You need to send something to the function, either the entire image element or just the src. You can do this:<img src="img1.gif" onclick="function1(this)" />function function1(img) {alert(img.src);}or this:<img src="img1.gif" onclick="function1(this.src)" />function function1(src) {alert(src);}Inside the function this does not refer to the image, it typically refers to the window object.
Ah, thanks so much. :)
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...