473,385 Members | 1,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Assigning dynamically declared event handlers to an object

Hello

I am new to creating objects in javascript, so please no flames about my
coding style. =) I am trying to create an object that will represent a "div"
element as a menu. I have written several methods that are working fine. The
problem is if I want to dynamically assign an event handler to the object,
the event handler is not called. What am I doing wrong? Below is a sample
HTML doc with everything in place.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<title>Menu Manager Test</title>
<script>
function testMenu (id)
{
this.addAttributes = addProperty;
this.addEvents = addProperty;

this.id = (id || 'mainMenu');
this.element = document.getElementById(this.id);
if (this.element == null)
{
this.element = document.createElement("<div id='" + this.id +
"'>Some Text</div>");
document.body.appendChild(this.element);
}
this.element.style.display = 'none';
}

function addProperty(propertyName,keyValue)
{
// this is a standalone property like an event or innerHTML
if (propertyName.indexOf("=") >= 0)
{
for (var i=0;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
this.element[arg[0]] = arg[1];
}
}
// this adds style elements
else
{
// args should be in the form of propertyname=value.
for (var i=1;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
this.element[addProperty.arguments[0]][arg[0]] = arg[1];
}
}
}

// Sample implementation in the HTML page

// Test function to check for use.
function testFunc()
{alert("here in testFunc.");}

var menuObj;
function setMenu(id)
{
// Create a new menu
menuObj = new testMenu(id);
// Adding a style works
menuObj.addAttributes("style","width=200");
menuObj.addAttributes("style","backgroundColor=gre en");
menuObj.addAttributes("style","color=white");
menuObj.addAttributes("style","border=1px solid black");
menuObj.addAttributes("style","textAlign=center");
menuObj.addAttributes("style","position=absolute") ;
menuObj.addAttributes("style","zindex=1000");
menuObj.addAttributes("style","top=200");
menuObj.addAttributes("style","left=300");
menuObj.addAttributes("innerHTML=A ball of string");
menuObj.addAttributes("style","display=");
// Dynamically assigning an event handler does not work.
menuObj.addEvents("onmouseover=testFunc()");
menuObj.addEvents("onmouseout=testFunc()");
}
</script>
</head>

<body onLoad="setMenu('mainMenu');">
</body>
</html>

Peace in Christ -
Ron Goral
Nov 17 '06 #1
7 2494
Daz

Ron Goral wrote:
Hello

I am new to creating objects in javascript, so please no flames about my
coding style. =) I am trying to create an object that will represent a "div"
element as a menu. I have written several methods that are working fine. The
problem is if I want to dynamically assign an event handler to the object,
the event handler is not called. What am I doing wrong? Below is a sample
HTML doc with everything in place.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<title>Menu Manager Test</title>
<script>
function testMenu (id)
{
this.addAttributes = addProperty;
this.addEvents = addProperty;

this.id = (id || 'mainMenu');
this.element = document.getElementById(this.id);
if (this.element == null)
{
this.element = document.createElement("<div id='" + this.id +
"'>Some Text</div>");
document.body.appendChild(this.element);
}
this.element.style.display = 'none';
}

function addProperty(propertyName,keyValue)
{
// this is a standalone property like an event or innerHTML
if (propertyName.indexOf("=") >= 0)
{
for (var i=0;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
this.element[arg[0]] = arg[1];
}
}
// this adds style elements
else
{
// args should be in the form of propertyname=value.
for (var i=1;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
this.element[addProperty.arguments[0]][arg[0]] = arg[1];
}
}
}

// Sample implementation in the HTML page

// Test function to check for use.
function testFunc()
{alert("here in testFunc.");}

var menuObj;
function setMenu(id)
{
// Create a new menu
menuObj = new testMenu(id);
// Adding a style works
menuObj.addAttributes("style","width=200");
menuObj.addAttributes("style","backgroundColor=gre en");
menuObj.addAttributes("style","color=white");
menuObj.addAttributes("style","border=1px solid black");
menuObj.addAttributes("style","textAlign=center");
menuObj.addAttributes("style","position=absolute") ;
menuObj.addAttributes("style","zindex=1000");
menuObj.addAttributes("style","top=200");
menuObj.addAttributes("style","left=300");
menuObj.addAttributes("innerHTML=A ball of string");
menuObj.addAttributes("style","display=");
// Dynamically assigning an event handler does not work.
menuObj.addEvents("onmouseover=testFunc()");
menuObj.addEvents("onmouseout=testFunc()");
}
</script>
</head>

<body onLoad="setMenu('mainMenu');">
</body>
</html>

Peace in Christ -
Ron Goral
Hi Ron.

I am a complete novice, but I will give you my 2 cents anyway.

First of all, I would recommend you save yourself a little bit of
bandwidth, and consider using CSS as opposed to:
menuObj.addAttributes("style","width=200");
menuObj.addAttributes("style","backgroundColor=gre en");
menuObj.addAttributes("style","color=white");
menuObj.addAttributes("style","border=1px solid black");
menuObj.addAttributes("style","textAlign=center");
menuObj.addAttributes("style","position=absolute") ;
menuObj.addAttributes("style","zindex=1000");
menuObj.addAttributes("style","top=200");
menuObj.addAttributes("style","left=300");
(This is not a flame, just a suggestion that might make life a little
easier).

As for the mouse events...

I can think of two mthods (which I cannot vouch for), that you may wish
to consider trying.
Firstly:
menuObj.addEvents("onmouseover=function() { testFunc(); }");
menuObj.addEvents("onmouseout=function() { testFunc(); }");

Secondly you could try:
menuObj.onmouseover=function() { testFunc(); }
menuObj.onmouseout=function() { testFunc(); }

Again, I can't stress enough how much of a beginner I am, but I think
it's worth a try.

I think the second one is most likely to work, but I can't be sure.
Please note, I have enclosed the function you wish to use within a
function(){} statement. I believe that if this isn't done, then the
function will be called as the script is loaded, and not actually
assigned to the event.

Best of luck.

Daz.

Nov 17 '06 #2

"Daz" <cu********@gmail.comwrote in message
news:11**********************@j44g2000cwa.googlegr oups.com...
Hi Ron.

I am a complete novice, but I will give you my 2 cents anyway.

First of all, I would recommend you save yourself a little bit of
bandwidth, and consider using CSS as opposed to:
menuObj.addAttributes("style","width=200");
menuObj.addAttributes("style","backgroundColor=gre en");
menuObj.addAttributes("style","color=white");
menuObj.addAttributes("style","border=1px solid black");
menuObj.addAttributes("style","textAlign=center");
menuObj.addAttributes("style","position=absolute") ;
menuObj.addAttributes("style","zindex=1000");
menuObj.addAttributes("style","top=200");
menuObj.addAttributes("style","left=300");
(This is not a flame, just a suggestion that might make life a little
easier).
I appreciate the suggestion. The idea of the addAttributes and addEvents
functions is to allow a person to define the menu in an HTML page without
accessing the .js file (where this will finally reside).
>
As for the mouse events...

I can think of two mthods (which I cannot vouch for), that you may wish
to consider trying.
Firstly:
menuObj.addEvents("onmouseover=function() { testFunc(); }");
menuObj.addEvents("onmouseout=function() { testFunc(); }");
This ^ does not work.
Secondly you could try:
menuObj.onmouseover=function() { testFunc(); }
menuObj.onmouseout=function() { testFunc(); }
This ^ does work.
Unfortunately, when the object code resides in a .js file, this is not going
to be feasible as I want the HTML author to be able to define the event in a
"<script></script>" block in his code.
Again, I can't stress enough how much of a beginner I am, but I think
it's worth a try.

I think the second one is most likely to work, but I can't be sure.
Please note, I have enclosed the function you wish to use within a
function(){} statement. I believe that if this isn't done, then the
function will be called as the script is loaded, and not actually
assigned to the event.
This does indeed happen.

Thank you for the suggestions. I am further along the road of understanding,
however, I am certain there must be a way to do this. I can't be the first
or only person to ever want to do this sort of thing. Am I? ;P

Peace -
Ron
Nov 17 '06 #3

"Daz" <cu********@gmail.comwrote in message
news:11**********************@j44g2000cwa.googlegr oups.com...
>
As for the mouse events...

I can think of two mthods (which I cannot vouch for), that you may wish
to consider trying.
Firstly:
menuObj.addEvents("onmouseover=function() { testFunc(); }");
menuObj.addEvents("onmouseout=function() { testFunc(); }");

Secondly you could try:
menuObj.onmouseover=function() { testFunc(); }
menuObj.onmouseout=function() { testFunc(); }

Again, I can't stress enough how much of a beginner I am, but I think
it's worth a try.

I think the second one is most likely to work, but I can't be sure.
Please note, I have enclosed the function you wish to use within a
function(){} statement. I believe that if this isn't done, then the
function will be called as the script is loaded, and not actually
assigned to the event.
eval() is the key. =)
The code considered the arguments being passed as strings. Of course, a
string cannot be executed, unless you use eval().

Using these modified calls:

menuObj.addEvents("event","onmouseover=function() { testFunc(); }");
menuObj.addEvents("event","onmouseout=function() { testFunc(); }");

And (greatly) modifying the addProperty function to be this:

function addProperty(propertyName,keyValue)
{
var type = (propertyName.indexOf("=") >= 0)?'standalone':propertyName;
for (var i=0;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
// something like innerHTML
if (type == 'standalone'){this.element[arg[0]] = arg[1];}
// an event property
else if (type == 'event'){this.element[arg[0]] = eval("function(){"
+ arg[1] + "}");}
// style and other named attributes
else {this.element[addProperty.arguments[0]][arg[0]] = arg[1];}
}
}

Produces the desired results. =)

Thanks for the help Daz.
Peace -
Ron
Nov 17 '06 #4

"Ron Goral" <ne**@uponthemountain.comwrote in message
news:qx*****************@newssvr25.news.prodigy.ne t...

This:

this.element[arg[0]] = eval("function(){"+arg[1]+"}");

Should be this:

this.element[arg[0]] = function(){eval(arg[1]);};
Nov 17 '06 #5
Daz

Ron Goral wrote:
"Ron Goral" <ne**@uponthemountain.comwrote in message
news:qx*****************@newssvr25.news.prodigy.ne t...

This:

this.element[arg[0]] = eval("function(){"+arg[1]+"}");

Should be this:

this.element[arg[0]] = function(){eval(arg[1]);};
Yes indeed. Does that mean it's working now?

Nov 18 '06 #6
Daz

Ron Goral wrote:
"Daz" <cu********@gmail.comwrote in message
news:11**********************@j44g2000cwa.googlegr oups.com...

As for the mouse events...

I can think of two mthods (which I cannot vouch for), that you may wish
to consider trying.
Firstly:
menuObj.addEvents("onmouseover=function() { testFunc(); }");
menuObj.addEvents("onmouseout=function() { testFunc(); }");

Secondly you could try:
menuObj.onmouseover=function() { testFunc(); }
menuObj.onmouseout=function() { testFunc(); }

Again, I can't stress enough how much of a beginner I am, but I think
it's worth a try.

I think the second one is most likely to work, but I can't be sure.
Please note, I have enclosed the function you wish to use within a
function(){} statement. I believe that if this isn't done, then the
function will be called as the script is loaded, and not actually
assigned to the event.

eval() is the key. =)
The code considered the arguments being passed as strings. Of course, a
string cannot be executed, unless you use eval().

Using these modified calls:

menuObj.addEvents("event","onmouseover=function() { testFunc(); }");
menuObj.addEvents("event","onmouseout=function() { testFunc(); }");

And (greatly) modifying the addProperty function to be this:

function addProperty(propertyName,keyValue)
{
var type = (propertyName.indexOf("=") >= 0)?'standalone':propertyName;
for (var i=0;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
// something like innerHTML
if (type == 'standalone'){this.element[arg[0]] = arg[1];}
// an event property
else if (type == 'event'){this.element[arg[0]] = eval("function(){"
+ arg[1] + "}");}
// style and other named attributes
else {this.element[addProperty.arguments[0]][arg[0]] = arg[1];}
}
}

Produces the desired results. =)

Thanks for the help Daz.
Peace -
Ron
Glad to have helped. Well done for figuring it out. :D

Nov 18 '06 #7
I wish to share this routine (for which I must lookup the source...)

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

obj is an HTMLElement; evType is a string like "click"; fn is a function
reference.

Let me elaborate on that last remark. This is a function definition:

function doWork(arg) {
alert(arg);
}

This is a corresponding function call:

doWork("'ello");

and this is the function reference:

doWork;

If you want to assign any function to a property like onclick, you must
assign the reference to the property:

thatDiv.onclick = doWork;

Alas, you cannot pass parameters to the function this way. Built-in
behaviour, nonetheless, is for the browser to pass the current event to
the function. Any event handling function should accept an event object
(unless you absolutely want to ignore the identity of the event, or do
not need its information). There is a little cross-browserity on it.
Microsofts browser does not pass the event, but has a global variable
'event' which carries the current event.

Lumping this together, your event handler function could look like

function doWork(e) {
if (!e) e = window.event;
// now you can be sure that e points to the current event object

// do whatever is necessary here
}

If you would put this:

thatDiv.onclick = doWork(argument);

doWork would be evaluated/executed, and its *result* is assigned to
onclick. Needless to say this will produce no effect when you actually
would click the element...

I have one other remark. When I create objects (classes, I like to call
them), I always include a private variable 'self' that is a copy of
'this'. It saves a lot of confusion as to what exactly this refers to,
when you are inside an object's functions.

function myObject() {
var self = this;

self.value = 0; // public member

// not really necessary here:
self.someMethod = functionname;

// nor here:
self.otherMethod = function(arg) {
// function body
self.value = 23; // 'this' would point to the function otherMethod!
}
}

This style may save you several "this.method is not a function" errors.

Ron Goral schreef:
Hello

I am new to creating objects in javascript, so please no flames about my
coding style. =) I am trying to create an object that will represent a "div"
element as a menu. I have written several methods that are working fine. The
problem is if I want to dynamically assign an event handler to the object,
the event handler is not called. What am I doing wrong? Below is a sample
HTML doc with everything in place.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<title>Menu Manager Test</title>
<script>
function testMenu (id)
{
this.addAttributes = addProperty;
this.addEvents = addProperty;

this.id = (id || 'mainMenu');
this.element = document.getElementById(this.id);
if (this.element == null)
{
this.element = document.createElement("<div id='" + this.id +
"'>Some Text</div>");
document.body.appendChild(this.element);
}
this.element.style.display = 'none';
}

function addProperty(propertyName,keyValue)
{
// this is a standalone property like an event or innerHTML
if (propertyName.indexOf("=") >= 0)
{
for (var i=0;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
this.element[arg[0]] = arg[1];
}
}
// this adds style elements
else
{
// args should be in the form of propertyname=value.
for (var i=1;i<addProperty.arguments.length;i++)
{
var arg = addProperty.arguments[i].split("=");
this.element[addProperty.arguments[0]][arg[0]] = arg[1];
}
}
}

// Sample implementation in the HTML page

// Test function to check for use.
function testFunc()
{alert("here in testFunc.");}

var menuObj;
function setMenu(id)
{
// Create a new menu
menuObj = new testMenu(id);
// Adding a style works
menuObj.addAttributes("style","width=200");
menuObj.addAttributes("style","backgroundColor=gre en");
menuObj.addAttributes("style","color=white");
menuObj.addAttributes("style","border=1px solid black");
menuObj.addAttributes("style","textAlign=center");
menuObj.addAttributes("style","position=absolute") ;
menuObj.addAttributes("style","zindex=1000");
menuObj.addAttributes("style","top=200");
menuObj.addAttributes("style","left=300");
menuObj.addAttributes("innerHTML=A ball of string");
menuObj.addAttributes("style","display=");
// Dynamically assigning an event handler does not work.
menuObj.addEvents("onmouseover=testFunc()");
menuObj.addEvents("onmouseout=testFunc()");
}
</script>
</head>

<body onLoad="setMenu('mainMenu');">
</body>
</html>

Peace in Christ -
Ron Goral

--
Bas Cost Budde
Holland
www.heuveltop.nl/BasCB/msac_index.html
Nov 18 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Thomas | last post by:
Hi, I'm having a problem with the dynamically created inputfields in Internet Explorer. The situation is the following: - I have a dynamically created table with a textbox in each Cell. - It...
9
by: Christopher Weaver | last post by:
Can anyone tell me how I could iterate through a collection of controls on a form while assigning their event handlers to another identical collection of controls on the same form. So far,...
1
by: Earl Teigrob | last post by:
PROBLEM: When a user control is loaded into a PlaceHolder control more than once, the events do not fire on the first click of a control on the dynamically loaded user control. In other words, the...
1
by: Greg | last post by:
In my ASP.NET application I have a button that when pressed, data needs to be saved based on what the user typed in. I have other controls on the same page that should be updated as a result of the...
2
by: Nathan Sokalski | last post by:
I would like to access variables and functions that I declare in the Global.asax.vb file. However, I am having trouble doing that. What does the declaration have to look like in the Global.asax.vb...
15
by: Iced Crow | last post by:
In C# I know that you can use delegates to assing multiple addresses of sub and functions to a delegate and have it fire multiple procedures... How do I do this in VB? I only know of assigning...
2
by: MLS | last post by:
The documentation on dynamic handlers comes across as abiguous. Perhaps somebody could help set me straight? I have a situation where I need to dynamically create several usercontrols of the...
13
by: Charles Law | last post by:
Mr "yEaH rIgHt" posted the following link about a week ago in answer to my question about removing event handlers. > http://www.vbinfozine.com/t_bindevt.shtml Following on from that post, the...
4
by: bjjnova | last post by:
I need help dynamically resetting an event handler. I have a form with several buttons. I have intialized the Click event of a particular button thus on the form: _button_3.Click += new...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.