How do I use this addEvent script?

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

I'm trying to call an action when someone clicks on an icon. Someone (I think it was Jeevesbond), gave me this code:

function addEvent(obj, evType, fn){
if (obj.addEventListener){
   obj.addEventListener(evType, fn, false);
   return true;
} else if (obj.attachEvent){
   var r = obj.attachEvent("on"+evType, fn);
   return r;
} else {
   return false;
}
}
'

That was awhile ago and now I don't know how to actually call it. I've tried a few variations and they don't work.

I've tried this:

  window.onload=function() {
addEvent(document.getElementById('datehelpicon'), 'click', alert('somethinghere'));
}
'

or this:

  window.onload=function() {
addEvent('datehelpicon', 'mouseover', alert('somethinghere'));
}
'

(the alert being a placeholder for the actual function...)

What am I supposed to be doing here???

He has: 629 posts

Joined: May 2007

You are almost there with your first version, Megan.

Instead of passing "alert('somethinghere')" as your third argument, pass the name of an actual function. Viz:

function myFun() {
    alert('somethinghere');
}
window.onload=function() {
    addEvent(document.getElementById('datehelpicon'), 'click', myFun);
};
'
Note that this version of addEvent fails in IE5 Mac. You probably don't care about that poor old thing, but here is the latest version that I know about, which has the added feature of retaining the "this" keyword in IE (Windows and Mac):

http://www.dustindiaz.com/rock-solid-addevent/

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

webwiz;221201 wrote: You are almost there with your first version, Megan.

Instead of passing "alert('somethinghere')" as your third argument, pass the name of an actual function. Viz:

function myFun() {
    alert('somethinghere');
}
window.onload=function() {
    addEvent(document.getElementById('datehelpicon'), 'click', myFun);
};
'

I have that working - my next question is whether I can streamline myFun so it would work for multiple elements. So could I do something like this?

function myFun(thingamie) {
    alert(thingamie);
}
window.onload=function() {
    addEvent(document.getElementById('datehelpicon'), 'click', myFun('valuehere'));
};
'

Does that make any sense? I'm trying to streamline this so I don't have to rewrite too many functions... or maybe I could create a function with the whole thing .... hmm....

This is the page I'm working with BTW:

http://www.housing.uwaterloo.ca/tempages/moving-late.html

(it may be in various states of disrepair when you access it - trying to get this to work if there are more than one tooltip on the page without rewriting whole chunks of javascript for each one)

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

Thanks David! I've seen many versions of this script that claim to be better than the others but I'm not sure which is the "best" one (especially since I don't need to support old browsers.) Even the one you linked to has a follow-up recommending a different method:

http://www.dustindiaz.com/yahoo-event-utility/

He has: 629 posts

Joined: May 2007

Yes. I have looked into the Yahoo library. My conclusion is that, unless you are using a lot of JavaScript effects etc. on a page, the Yahoo library is a bit of overkill.

Ultimately, it's a design choice. Like most design choices, it's a matter of compromise, rather than there being a single, "correct" solution. "Yer pays yer money ..."

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

He has: 629 posts

Joined: May 2007

Hey, Megan,
If you are at the U. of Waterloo, Canada, don't waste time with amateurs like me. Locate Mike Purvis, a brilliant student and far more worthy of the moniker "web wiz" than I --

http://uwmike.com/

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

Thanks for the reference Smiling I found some other problems with that script (namely that you run into problems with the positioning when the icon is placed within a paragraph or other element). I decided to forget about trying to get it to work for block level elements and just used this simple CSS solution instead:

http://psacake.com/web/jl.asp

Simple and easy. I'm not thrilled with the concept of putting the tooltip inside the link, or in a span (should be a paragraph), but I've spent way too much time trying to figure this out already...

I am still interested in getting this to work for block level elements. You can't do that with the solution I linked because the tooltip text is in a span.

He has: 629 posts

Joined: May 2007

Quote: I am still interested in getting this to work for block level elements. You can't do that with the solution I linked because the tooltip text is in a span.

I'm not sure what you mean by this, Megan. If it's a tooltip you are after, then, yes, that CSS solution is easier to write and maintain than a script. To get it to work in IE6 and older, the :hover only works on an "a" element. Because an "a" element can only contain inline elements, you are correct in noting you are restricted to a "span" or similar inline element. For modern browsers and IE7, you can add :hover to whatever you like.

Dean Edwards has written something he calls "IE7"[1] -- a JavaScript that makes IE6 more CSS capable. That may be overkill for your requirements, though.

Can you please explain exactly what you hope to achieve? At the moment, I am only guessing.

[1] http://dean.edwards.name/IE7/intro/

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

The hover is on the a element. It works fine in IE 6. And I knew I was correct that you can't put block tags in a span. That's pretty basic Wink

What I'm trying to do is find a way to do the same thing but include block level elements. I was almost there with my previous example but would have to position the tooltip differently. The work in progress is now here:

[url]http://www.housing.uwaterloo.ca/tempages/moving-late(tooltips).html[/url]

The first problem is that the tooltip is currently positioned relative to it's contiaining div, which isn't working right now for the second example where the icon is located in the middle of the paragraph.

The second problem is that there is a lot of repetition of code for each time you call the tooltip. It would be nice if you didn't have to rewrite the event handlers each time you wanted a tooltip. It would be nice if I could consolidate that part and the toggle functions they refer to into one function that would be set for all the tooltips. That would make it much easier to re-use.

He has: 629 posts

Joined: May 2007

Ah! Okay, now I see what you are trying to do.

I think you are looking for a "getElementsByClassName" function. That way, you can create an array of your 'class="icon"' elements and loop through it to attach your "mouseover" and "mouseout" events. You may want to add "focus" and "blur" events for keyboard users as well.

function walkTheDOM(node, func) {
  func(node);
  node = node.firstChild;
  while(node) {
    walkTheDOM(node, func);
    node = node.nextSibling;
  }
}

function getElementsByClassName(className) {
    var results = [];
    walkTheDOM(document.body, function(node) {
        var a, c = node.className, i;
        if (c) {
            a = c.split(' ');
            for (i=0; i<a.length; i++) {
                if (a[i] === className) {
                    results.push(node);
                    break;
                }
            }
        }
    });
    return results;
}
'
More stuff on those lines here:
http://getelementsby.com/

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

I already have a getElementsByClassName function - what I need to do is bundle it together with the event handlers.

(no time to work on this right now - might revisit it later)

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.