Question

So I want an element i.e: <a id="target">click me</a> to perform a JavaScript function i.e: functionName();
I want to avoid using the "on" attributes i.e: onclick="".
By cross-browser I mean the A-grade browser compatibility list from YUI

Was it helpful?

Solution

var el = document.getElementById("target");
var old = el.onclick;
el.onclick = function() {
  if(old) old();
  functionName();
  // if you want to prevent default action
  // return false; 
};​

For a more robust solution, see: Dean Edward's addEvent.

OTHER TIPS

document.getElementById('target').onclick=function() {
  functionName();
  return false;
}

I assume you meant "without onclick html attribute"

Use the getElementById method to find the element, and set it's onclick event:

document.getElementById('target').onclick = functionName;

I don't know if this counts as a library, but here are the addEvent() and removeEvent() functions written by John Resig (yes, that John Resig):

function addEvent( obj, type, fn )
{
    if (obj.addEventListener)
    {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent)
    {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); };
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
}

function removeEvent( obj, type, fn )
{
    if (obj.removeEventListener)
    {
        obj.removeEventListener( type, fn, false );
    }
    else if (obj.detachEvent)
    {
        obj.detachEvent( "on"+type, obj[type+fn] );
        obj[type+fn] = null;
        obj["e"+type+fn] = null;
    }
}

Use:

addEvent(document.getElementById('target'), 'click', functionName);
removeEvent(document.getElementById('target'), 'click', functionName);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top