JontyDunne
asked on
Attaching events using the DOM
Hi there,
I've just discovered I have a major dilemma here. I've found out that when attaching an event to an element using the attachElement() method of the document object you can't actually stipulate any parameters in the function that you attach as otherwise the function executes there and then. Does anyone know of a good solution to overcoming this problem? Is it possible to use the setAttribute() method? For example:
object.setAttribute("onMou seOver", "foo(parameters)")
I have tried this but I though there might be some case sensitivity issue here as it doesn't work at the moment. It doesn't throw any errors but the function that should be called doesn't work.
Anyone got any ideas? This is urgent. You will be rewarded well for your efforts ;o)
Regards,
Jonty
I've just discovered I have a major dilemma here. I've found out that when attaching an event to an element using the attachElement() method of the document object you can't actually stipulate any parameters in the function that you attach as otherwise the function executes there and then. Does anyone know of a good solution to overcoming this problem? Is it possible to use the setAttribute() method? For example:
object.setAttribute("onMou
I have tried this but I though there might be some case sensitivity issue here as it doesn't work at the moment. It doesn't throw any errors but the function that should be called doesn't work.
Anyone got any ideas? This is urgent. You will be rewarded well for your efforts ;o)
Regards,
Jonty
Oh, both methods have the name: anonymous functions.
ASKER
Okay I understand what you've done there but I actually need to call a function and pass parameters to it too. This function that I want to call is already setup as well. I've just read somewhere that the setAttribute() does actually set the attribute for onMouseOver, onMouseOut etc but the function set for these attributes doesn't execute in IE5+. There must be some way around this surely?
Cheers,
Jonty
Cheers,
Jonty
Like this:
object.setAttribute("onMou seOver", function(){foo(parameters) });
object.setAttribute("onMou
This works
<form name='f'>
<input type='button' name='b' >
</form>
<script>
function colour(s){
document.bgColor=s
}
s='red'
document.forms[0].elements
</script>
further example
<form name='f'>
<input type='button' value="change color">
<input type='button' value="set color red" onclick="s='red'">
<input type='button' value="set color blue" onclick="s='blue'">
</form>
<script>
function colour(s){
document.bgColor=s
}
s='red'
document.forms[0].elements [0].onclic k=function (){colour( s)}
</script>
<form name='f'>
<input type='button' value="change color">
<input type='button' value="set color red" onclick="s='red'">
<input type='button' value="set color blue" onclick="s='blue'">
</form>
<script>
function colour(s){
document.bgColor=s
}
s='red'
document.forms[0].elements
</script>
ASKER
Okay NetGroove, unfortunately yours did not work.
Xxavier, yours did work for which I am thankful but is there no neater way of doing this? It's messy code in my opinion.
Thanks,
Jonty
Xxavier, yours did work for which I am thankful but is there no neater way of doing this? It's messy code in my opinion.
Thanks,
Jonty
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Sorry I explained that really badly.
Your code is very neat. What I should have said is, why does it only work with the anonymous function(){} round the function that you want to execute? Is there no way of doing it without this anonymous function?
Cheers,
Jonty
Your code is very neat. What I should have said is, why does it only work with the anonymous function(){} round the function that you want to execute? Is there no way of doing it without this anonymous function?
Cheers,
Jonty
I must confess I do not know off the top of my head and I do not have my JS bible with me, documentation on the web is spotty. I have always done it that way and since it has worked I never enquired further. It possibly could well be done better I don't know.
ASKER
Okay,
Thanks for your help. I can't find any other solutions on the web either. Seems strange not to find any though as I thought this would be an important topic once this problem was discovered.
Anyhow, thanks again,
Jonty
Thanks for your help. I can't find any other solutions on the web either. Seems strange not to find any though as I thought this would be an important topic once this problem was discovered.
Anyhow, thanks again,
Jonty
>>>Is there no way of doing it without this anonymous function?
<html>
<body>
<script>
function runit()
{
var tds = document.getElementsByTagN ame("TD")
for (i=0;i<tds.length;i++)
{
tds[i].onmouseover=red;
}
}
function red()
{
this.style.backgroundColor ='red'
}
</script>
<table width=555 cellspacing=0 cellpadding=0 border=1>
<td> </td>
<td> </td>
<td> </td>
</table>
<br><br>
<button onclick=runit()>attach event onmouse over</button>
</body>
</html>
<html>
<body>
<script>
function runit()
{
var tds = document.getElementsByTagN
for (i=0;i<tds.length;i++)
{
tds[i].onmouseover=red;
}
}
function red()
{
this.style.backgroundColor
}
</script>
<table width=555 cellspacing=0 cellpadding=0 border=1>
<td> </td>
<td> </td>
<td> </td>
</table>
<br><br>
<button onclick=runit()>attach event onmouse over</button>
</body>
</html>
Does this also not work for you:
object.setAttribute("onMou seOver", new Function(" foo(parameters) ") );
object.setAttribute("onMou
Hi Jonty,
is this what you are looking for? watch the text box & alerts
<FORM name="a">
<INPUT ID="counter1" STYLE="position:relative; left:10px" TYPE="button" VALUE="Click Me"><br>
<input type="text" name="b">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
var obj = document.getElementById('c ounter1');
var xlocation = parseInt(obj.style.left);
document.getElementById('c ounter1'). attachEven t("onclick ", firstClick);
document.getElementById('c ounter1'). attachEven t("onclick ", secondClick);
function firstClick() {
document.a.b.value="first Click";
}
function secondClick()
{
if (document.a.b.value != "")
alert("second click came second");
else
alert('second click came first')
obj.setAttribute('counter1 ','from set')
attr = obj.getAttribute('counter1 ')
document.a.b.value = attr;
alert(obj.getAttribute('co unter1'))
}
alert(obj.getAttribute('co unter1'))
//-->
</SCRIPT>
Vinny
is this what you are looking for? watch the text box & alerts
<FORM name="a">
<INPUT ID="counter1" STYLE="position:relative; left:10px" TYPE="button" VALUE="Click Me"><br>
<input type="text" name="b">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
var obj = document.getElementById('c
var xlocation = parseInt(obj.style.left);
document.getElementById('c
document.getElementById('c
function firstClick() {
document.a.b.value="first Click";
}
function secondClick()
{
if (document.a.b.value != "")
alert("second click came second");
else
alert('second click came first')
obj.setAttribute('counter1
attr = obj.getAttribute('counter1
document.a.b.value = attr;
alert(obj.getAttribute('co
}
alert(obj.getAttribute('co
//-->
</SCRIPT>
Vinny
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I hadn't yet seen Vinny's post when I wrote mine. I see he employs a similar methodology with regard to storing values in custom element attributes.
Note that attachEvent() is MSIE-only. Mozilla and Opera both use addEventListener().
BTW, you can use anonymous functions in addEventListener() and attachEvent(). (I'll bet that's what you really wanted to hear, eh? <grin>). Example:
function addEvent(elementObject, eventName, functionObject)
{
if(document.addEventListen er)
elementObject.addEventList ener(event Name, functionObject, false);
else
if(document.attachEvent)
elementObject.attachEvent( "on" + eventName, functionObject);
}
window.timesClicked = 0;
window.onload
= function()
{
var theP = document.getElementsByTagN ame("p")[0 ];
addEvent(theP, "click", function() { alert(window.timesClicked+ +);});
};
Note that I corrected an error in my bridging function.
Above tested in MSIE 6.0, Mizlla 1.5, and Opera 7.12.
HTH,
jon.
Note that attachEvent() is MSIE-only. Mozilla and Opera both use addEventListener().
BTW, you can use anonymous functions in addEventListener() and attachEvent(). (I'll bet that's what you really wanted to hear, eh? <grin>). Example:
function addEvent(elementObject, eventName, functionObject)
{
if(document.addEventListen
elementObject.addEventList
else
if(document.attachEvent)
elementObject.attachEvent(
}
window.timesClicked = 0;
window.onload
= function()
{
var theP = document.getElementsByTagN
addEvent(theP, "click", function() { alert(window.timesClicked+
};
Note that I corrected an error in my bridging function.
Above tested in MSIE 6.0, Mizlla 1.5, and Opera 7.12.
HTH,
jon.
To get a custom attribute to work, I had to use:
window.onload = countClicks;
function countClicks()
{
var theP = document.getElementsByTagN ame("p")[0 ];
if(theP.getAttribute("time sClicked") == "" || theP.getAttribute("tmiesCl icked") == null)
theP.setAttribute("timesCl icked", "0");
if(document.addEventListen er)
theP.addEventListener("cli ck", function() { var t = this.getAttribute("timesCl icked"); alert(t++); this.setAttribute("timesCl icked", t+""); }, false );
else
if(document.attachEvent)
theP.attachEvent("onclick" , function() { var el = window.event.srcElement; var t = el.getAttribute("timesClic ked"); alert(t++); el.setAttribute("timesClic ked", t+""); });
}
Notes:
1. For a custom attribute that's not yet been set, MSIE returns null instead of an empty string. Mozilla and Opera both return an empty string for an unset attribute whether it's part of the spec or not. This is a matter of interpretation by the different browser vendors and neither behaviour is really "correct" or "incorrect" in this regard as best I can determine. Although I do find the MSIE behaviour inconvenient. ;-)
2. In MSIE, the "this" keyword in event handlers assigned via anonymous functions as parameters to attachEvent() resolves to Window. You have to a reference the target element via the global event object (which seems silly to me since "this" is the event target in most if not all other circumstances). I suppose I should rewrite the example to use a named function, but maybe I'll do that later. Right now I need a fresh cuppa.
window.onload = countClicks;
function countClicks()
{
var theP = document.getElementsByTagN
if(theP.getAttribute("time
theP.setAttribute("timesCl
if(document.addEventListen
theP.addEventListener("cli
else
if(document.attachEvent)
theP.attachEvent("onclick"
}
Notes:
1. For a custom attribute that's not yet been set, MSIE returns null instead of an empty string. Mozilla and Opera both return an empty string for an unset attribute whether it's part of the spec or not. This is a matter of interpretation by the different browser vendors and neither behaviour is really "correct" or "incorrect" in this regard as best I can determine. Although I do find the MSIE behaviour inconvenient. ;-)
2. In MSIE, the "this" keyword in event handlers assigned via anonymous functions as parameters to attachEvent() resolves to Window. You have to a reference the target element via the global event object (which seems silly to me since "this" is the event target in most if not all other circumstances). I suppose I should rewrite the example to use a named function, but maybe I'll do that later. Right now I need a fresh cuppa.
This works with IE6, Mozilla 1.7.3, FireFox 1.0:
<script language="JavaScript">
eventHandler("myObject", "onclick", "testAlert()");
}
function testAlert() {
alert("After !!");
}
function eventHandler(oItem,eventHa ndler,acti on) {
document.getElementById(oI tem)[event Handler] = new Function(action);
}
</script>
<a href="JavaScript:void(0);" id="myObject" onclick="alert('before...' )">Test</a >
<br>
<button onClick="testAttribute()"> change event</button>
I repeat, it works very fine !!!
<script language="JavaScript">
eventHandler("myObject", "onclick", "testAlert()");
}
function testAlert() {
alert("After !!");
}
function eventHandler(oItem,eventHa
document.getElementById(oI
}
</script>
<a href="JavaScript:void(0);"
<br>
<button onClick="testAttribute()">
I repeat, it works very fine !!!
Here is a full code with testAttributes() function :
<html>
<body>
<script language="JavaScript">
function testAttribute() {
eventHandler("myObject", "onclick", "testAlert()");
}
function testAlert() {
alert("After !!");
}
function eventHandler(oItem,eventHa ndler,acti on) {
document.getElementById(oI tem)[event Handler] = new Function(action);
}
</script>
<a href="JavaScript:void(0);" id="myObject" onclick="alert('before...' )">Test</a >
<br><br>
<button onClick="testAttribute()"> change event</button>
</body>
</html>
Sorry
<html>
<body>
<script language="JavaScript">
function testAttribute() {
eventHandler("myObject", "onclick", "testAlert()");
}
function testAlert() {
alert("After !!");
}
function eventHandler(oItem,eventHa
document.getElementById(oI
}
</script>
<a href="JavaScript:void(0);"
<br><br>
<button onClick="testAttribute()">
</body>
</html>
Sorry
object.onmouseover = function(){this.style.back
Or like this:
object.onmouseover = new Function("this.style.backg
Good luck,
NetGroove