Append Click Listener

Intro

This demo shows how to append a click listener to all <A> elements whose contained IMG src matches a particular string.

Demo

This link will get a new listener appended. This one will not.

Source

window.onload = function()
{
  appendClickListener("cat_sleep", newClickListener);
}

function appendClickListener(sImgUrl, fnListener)
{
  if (document.getElementsByTagName) {
    var a, aList = document.getElementsByTagName("A");
    for (var i = 0; i < aList.length; i++) {
      a = aList[i];
      if (a.innerHTML && a.innerHTML.match(sImgUrl)) {
        if (a.addEventListener) {
          a.addEventListener('click', fnListener, false);
        }
        else if (a.attachEvent) {
          a.attachEvent('onclick', fnListener);
        }
        else {
          a.onclick_old = a.onclick;
          a.onclick = fnListener;
        }
      }
    }
  }
}

function newClickListener(e)
{
  if (this.onclick_old) {
    this.onclick_old();
  }
  alert('in newClickListener()');
}

function oldClickListener()
{
  alert('in oldClickListener()');
}

Tech Support

Forum support is available at the X Library Support Forums.