Reputation: 95
I have a button with an onclick event as follows:
<button type="button" onclick="captions(event)">
<img src="someimg.png">
</button>
I need to be able to change the img src without using an ID to reference it. I want to pass "this" and the event (I need to do some other things that require event to be passed) but I cannot get this to work. Example of JS is below:
function captions(event) {
this.src = this.src.replace("img2.png");
}
Thanks!
Upvotes: 1
Views: 129
Reputation: 7950
If you want to do an inline onclick
event, you should simply be able to pass a new variable that captures the element into the function, like this:
function captions(element, event) {
. . . do stuff . . .
}
Then you would call it, passing this
in for the element
parameter, like this:
<button type="button" onclick="captions(this, event);">
<img src="someimg.png">
</button>
Upvotes: 0
Reputation: 91
You can get the element that was clicked using the event.target property (http://www.w3schools.com/jsref/event_target.asp).
function captions(event) {
event.target.src = "img2.png";
}
Here is a jsfiddle.
Upvotes: 1
Reputation: 227200
I suggest not using inline event handlers. You should bind the event "unobtrusively" using JavaScript.
First give the button a class:
<button type="button" class="captions">
<img src="someimg.png">
</button>
Then bind the event:
window.onload = function(){
var captions = document.getElementsByClassName('captions');
for(var i = 0, len = captions.length; i < len; i++){
captions[i].addEventListener('click', function(event){
// this is your button, what you clicked on
// you need to get the image
var image = this.getElementsByTagName('img')[0];
// this.src.replace("img2.png") doesn't do what you think it does
// String.replace takes 2 parameters
image.src = '/your/new/image';
});
}
};
DEMO: http://jsfiddle.net/WcFzq/
Upvotes: 1
Reputation: 23208
Following will solve your problem.
function captions(event) {
var img = this.childNodes[0];
img.src = img.src.replace("img2.png");
}
Upvotes: 0