title: JavaScript - Loop over all a tags, add an onclick to each one
body: <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>function prepareLinks(){
  var links = document.getElementsByTagName('a');
  for(var i=0; i&lt;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();
  </code></pre>
  
  <p>...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?</p>