JavaScript - Loop over all a tags, add an onclick to each one

Posted by tripRev on Stack Overflow See other posts from Stack Overflow or by tripRev
Published on 2012-04-12T23:22:44Z Indexed on 2012/04/12 23:29 UTC
Read the original article Hit count: 160

Filed under:

I've got a list of links that point to images, and a js function that takes a URL (of an image) and puts that image on the page when the function is called.

I was originally adding an inline onlick="showPic(this.getAttribute('href'))" to each a, but I want to separate out the inline js. Here's my func for adding an onclick to each a tag when the page loads:

function prepareLinks(){
var links = document.getElementsByTagName('a');
for(var i=0; i<links.length; i++){
    var thisLink = links[i];
    var source = thisLink.getAttribute('href'); 
    if(thisLink.getAttribute('class') == 'imgLink'){
        thisLink.onclick = function(){
            showPic(source);
            return false;
        }
    }
}
}

function showPic(source){
var placeholder = document.getElementById('placeholder');
placeholder.setAttribute('src',source);
}

window.onload = prepareLinks();

...but every time showPic is called, the source var is the href of the last image. How can I make each link have the correct onclick?

© Stack Overflow or respective owner

Related posts about JavaScript