« Blog Home

§ Adding events to elements

For most elements, you can just do element.onclick = function_name.  But read on...

(Much better article available at Add and Remove Elements with JavaScript (reprise) from Dustin Diaz.)

This is used here and there; this is part of the Simple tabbed interface entry.

First there's the makeDoubleDelegate function to add the window.onload safely.  But for most other elements, you can just do element.onclick = function_name.  Remember NOT to use () for these assignments.


function adminTabClick () {
  var tabas=this.getElementsByTagName("a");
  location.href=tabas[0].href;
}
function setActiveAdminTab(tabnum) {
    var tabsarray = document.getElementById("adminlinks").getElementsByTagName("span");
  for (var i=0; i<tabsarray.length; i++) {
    tabsarray[i].className="";
  }
  tabsarray[tabnum].className="activeadmintab";
}
function adminTabMouseover() {
  if(this.className!="activeadmintab")
    this.className="highlightadmintab";
}
function adminTabMouseout() {
  if(this.className!="activeadmintab")
    this.className="";
}
function addAdminTabMouseEvents() {
  var admindiv=document.getElementById("adminlinks");
  if(admindiv) {
    var tabslist=admindiv.getElementsByTagName("span");
    for(var i=0;i<tabslist.length;i++) {
      tabslist[i].onmouseover=adminTabMouseover;
      tabslist[i].onmouseout=adminTabMouseout;
      tabslist[i].onclick=adminTabClick;
    }
  }
}
function makeDoubleDelegate(function1, function2) {
  return function() {
    if (function1)
      function1();
    if (function2)
      function2();
  }
}
window.onload = makeDoubleDelegate(window.onload, addAdminTabMouseEvents );
 


Type more text here.

last edited on January 14th, 2010 at 2:19 PM

Comments

No Comments Here. Add yours below!

Add your comment

Name:
Email: (Will not be displayed - Privacy policy)
Website:
Comments:
  random image I can't read it!
Give me a different one!
Verify Post: Input the text from the image above to verify this post (helps prevent spam)
 

« Blog Home


“Sure, sure.  Back in the old days, when you had to walk to school, through the snow, in the broiling heat, uphill both ways, barefoot, carrying your clay tablet and a sharp stylus through the rain, and -”
Clarissa, In Fury Born, David Weber