Link to home
Start Free TrialLog in
Avatar of JontyDunne
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("onMouseOver", "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
Avatar of NetGroove
NetGroove

Do it like this:

   object.onmouseover = function(){this.style.backgroundColor='red'};

Or like this:

   object.onmouseover = new Function("this.style.backgroundColor='red';");


Good luck,
NetGroove


Oh, both methods have the name: anonymous functions.

Avatar of JontyDunne

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
Like this:

  object.setAttribute("onMouseOver", function(){foo(parameters)});





This works

<form name='f'>
<input type='button' name='b' >
</form>

<script>
function colour(s){
document.bgColor=s
}
s='red'
 document.forms[0].elements[0].onclick=function(){colour(s)}
</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].onclick=function(){colour(s)}

</script>
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
ASKER CERTIFIED SOLUTION
Avatar of Xxavier
Xxavier
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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.
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
Avatar of devic
>>>Is there no way of doing it without this anonymous function?


<html>
<body>
<script>
function runit()
{
      var tds = document.getElementsByTagName("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>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
</table>
<br><br>
<button onclick=runit()>attach event onmouse over</button>
</body>
</html>
Does this also not work for you:

  object.setAttribute("onMouseOver", new Function(" foo(parameters) ")  );


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('counter1');

var xlocation = parseInt(obj.style.left);

document.getElementById('counter1').attachEvent("onclick", firstClick);

document.getElementById('counter1').attachEvent("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('counter1'))
}

alert(obj.getAttribute('counter1'))
//-->
</SCRIPT>

Vinny
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.addEventListener)
    elementObject.addEventListener(eventName, functionObject, false);
  else
    if(document.attachEvent)
      elementObject.attachEvent("on" + eventName, functionObject);
}

window.timesClicked = 0;

window.onload
  = function()
    {
      var theP = document.getElementsByTagName("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.
To get a custom attribute to work, I had to use:

window.onload = countClicks;

function countClicks()
{
  var theP = document.getElementsByTagName("p")[0];
  if(theP.getAttribute("timesClicked") == "" || theP.getAttribute("tmiesClicked") == null)
    theP.setAttribute("timesClicked", "0");

  if(document.addEventListener)
    theP.addEventListener("click", function() { var t = this.getAttribute("timesClicked"); alert(t++); this.setAttribute("timesClicked", t+""); }, false );
  else
    if(document.attachEvent)
      theP.attachEvent("onclick", function() { var el = window.event.srcElement; var t = el.getAttribute("timesClicked"); alert(t++); el.setAttribute("timesClicked", 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.
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,eventHandler,action) {
      document.getElementById(oItem)[eventHandler] = 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 !!!
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,eventHandler,action) {
     document.getElementById(oItem)[eventHandler] = 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