I’m exploring some sample code from a book. The code has a set of thumbnails like this:
<div id="thumbnailPane">
<img src="images/itemGuitar.jpg" alt="guitar" width="301" height="105"
title="itemGuitar" id="itemGuitar" />
<img src="images/itemShades.jpg" alt="sunglasses" width="301" height="88"
title="itemShades" id="itemShades" />
<img src="images/itemCowbell.jpg" alt="cowbell" width="301" height="126"
title="itemCowbell" id="itemCowbell" />
<img src="images/itemHat.jpg" alt="hat" width="300" height="152"
title="itemHat" id="itemHat" />
</div>
When a thumbnail is clicked, it brings out a larger image with this function:
function initPage() {
// find the thumbnails on the page
thumbs = document.getElementById("thumbnailPane").getElementsByTagName("img");
// set the handler for each image
for (var i = 1; i < thumbs.length; i++) {//CHANGED FROM 0 TO 1
image = thumbs[i];
// create the onclick function
image.onclick = function() {
// find the image name
detailURL = 'images/' + this.title + '-detail.jpg';
document.getElementById("itemDetail").src = detailURL;
getDetails(this.title);
}
}
}
I understand how that works. What I am wondering is whether it would be possible to replicate that with a single hard coded function. Basically what I’d like is to get the title of a thumbnail when it is clicked with a single common function for all thumbnails that would be called with an onclick event handler (onclick="getImage()").
How do I get the title or the id of the element that was just clicked?
I do not use jQuery, so I need a JS answer please.
EDIT:
I have tried to write a getImage() function like this:
function getImage(){
var title = this.title;
detailURL='images/' + title + '-detail.jpg';
document.getElementById("itemDetail").src = detailURL;
}
This doesn’t work. The value of var title is "undefined".
You would pass the element to the handler, and define a parameter
getImage.Or better, you’d
.callthe handler, so you can still usethisingetImage.But overall, you don’t need an inline handler to reuse a function. Just make a named function, and assign it in your JavaScript code. It’ll just work.