PDA

View Full Version : Dynamically adding onMousover Handler


JustAnotherCode
03-16-2003, 11:28 PM
I'm having problems adding an onmouseover handler to objects I dynamically create.

I have the arrays created in the head of the page:


numwords=0;
poedivs = new Array();
poewords = new Array();


then.. a constructor

function word(text) {
numwords++;
this.text = text;
this.idnum = numwords;
poedivs[numwords] = document.createElement("DIV");
document.body.appendChild(poedivs[numwords]);
poedivs[numwords].innerHTML = text;
poedivs[numwords].style.cssText = "position:absolute; left:20px;top:200px; border:solid; border-width:2px";
//poedivs[numwords].attachEvent("onmouseover",alert());
}


I think these are both accurate. I seem to be able to create a new object while in the body of the page:

poewords[0] = new word("word");


however, I can't figure out how to add a handler for the onmouseover event to the dynamically created object. The last line there of the second code block, the one that's commented off, is one thing I've tried. doesn't work. it just gives an alert as the page loads. any suggestions?

btw... I only care if it works in IE6.

cheesebagpipe
03-16-2003, 11:51 PM
poedivs[numwords].attachEvent("onmouseover",alert);

You're setting a pointer (reference) to the window.alert property - which contains the function in question - not calling it. The operator pair (()) calls functions, it's not part of a function's name, which is just the name of the object property where the function object is stored. No comment on your browser preferences...

http://www.scottandrew.com/weblog/articles/cbs-events

JustAnotherCode
03-17-2003, 12:00 AM
thanks! so, if I were to use a different function, would I just say functionname instead of functionname()?
What if I wished to pass a value to the function. sorry to be so bothersome. and, thanks again for the reply.


as for my browser choice, it's based on the fact that I'm writing this program for my own amusement. my target audience is....: me.

cheesebagpipe
03-17-2003, 12:22 AM
No bother. To your target audience:

Pass arguments by using a wrapper function (object) 'around' the function you're calling from the handler. The wrapper is 'anonymous'; unlike functions exposed by the browser itself (like window.alert) or ones you create with the function keyword, which are, by default, window properties, anonymous functions are assigned directly:

poedivs[numwords].attachEvent("onmouseover", function() {alert("foo")});

You can also use the Function(), erm, constructor function:

poedivs[numwords].attachEvent("onmouseover", new Function('alert("foo")');

Or - just declare the function the typical way:

function foo() { alert('foo') }

...and use the pointer approach:

poedivs[numwords].attachEvent("onmouseover", foo);

JustAnotherCode
03-17-2003, 12:30 AM
worked fine. that's what I needed. thanks once again!