§ 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
Categories
Comments
- Walid on "Adventures with Ubuntu 9.10 on G4 Yikes!" - I am in the same process as you. Although I still dual-boot to Windows for my ganimg leisure. My first contact with Ubuntu was way…
- Slashback on "Simpler adding & removing element classnames" - Actually, the addClassName function does what you want, pretty much the same way you suggest.
- angie on "Simpler adding & removing element classnames" - And what if I want to add a class, but keeping the csseals the element already has?I mean, I have an element with a class, let's name…
- backlinks on "Adjust iframe height to contents" - Definitely helped me.
- Slashback on "Simpler validate form fields are filled in (no additional class names)" - You are welcome!