• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1642
  • Last Modified:

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
0
JontyDunne
Asked:
JontyDunne
  • 4
  • 4
  • 4
  • +4
3 Solutions
 
NetGrooveCommented:
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


0
 
NetGrooveCommented:
Oh, both methods have the name: anonymous functions.

0
 
JontyDunneAuthor Commented:
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
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
NetGrooveCommented:
Like this:

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




0
 
XxavierCommented:

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>
0
 
XxavierCommented:
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>
0
 
JontyDunneAuthor Commented:
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
0
 
XxavierCommented:
Basically I have

objectName.event=function(){functionName(paramlist)}

I am hard pushed to make it neater than that
0
 
JontyDunneAuthor Commented:
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
0
 
XxavierCommented:
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.
0
 
JontyDunneAuthor Commented:
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
0
 
devicCommented:
>>>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>
0
 
NetGrooveCommented:
Does this also not work for you:

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


0
 
VincentPugliaCommented:
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
0
 
ZontarCommented:
First, in case you missed it, let me point to my previous answer here: http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20784930.html#9663116

Additional comment: I have a tendency to 'stack' anonymous functions, e.g.

window.onload
  = function()
     {
        var myEl = document.getElementById("someElement");
        myEl.onclick = function() { alert("You clicked on a <" + this.tagName.toUpperCase() + "> tag."); };
     };

and devic's example is a bit neater in this regard.

The problem with passing parameters to event handlers is that the event handler functions have their own scopes. Two ways I use to get around this are:

1. To assign the parameters as values to elements. For example

window.onload
  = function()
    {
      var theP = document.getElementsByTagName("p")[0];
      theP.setAttribute("timesClicked", "0");
      theP.onclick
        = function()
          {
            var t = this.getAttribute("timesClicked");
            alert(t++);
            this.setAttribute("timesClicked", t+"");
          };
    };

or

2. To make them global by assigning them as properties of the Window object

window.timesClicked = 0;

window.onload = showTimesClicked;

function showTimesClicked()
{
  var theP = document.getElementsByTagName("p")[0];
  theP.onclick = function() { alert(window.timesClicked++); };
};

More event-handling fun ensues:

The W3C way to assign event handlers is to use addEventListener(). The basic syntax is:

elementObject.addEventListener("eventName", functionName, useCapture);

If useCature is true, all events of the type indicated will be be routed to the event listener function before reaching any descendants of the specified element, and events bubbling up through the document tree are ignored. Normally, you just set this to false.

For example,

document.getElementById("myElement").addEventListener("click", showTimesClicked, false);

MSIE doesn't support this. Instead it uses an attachEvent() method which takes the event handler name (instead of the event name) and the name of the function to be called:

document.getElementById("myElement").attachEvent("onclick", showTimesClicked);

I believe you can test to see which one's supported by using something like

//  prototype: addEvent(HTMLElement elementObject, String eventName, Object functionObject)
function addEvent(elementObject, eventName, functionObject)
{
  if(document.addEventListener)
    elementObject.addEventListener("on" + eventName, functionObject);
  else
    if(document.attachEvent)
      elementObject.attachEvent(eventName, functionObject);
}

Enjoy.
0
 
VincentPugliaCommented:
<FORM name="a">
<INPUT ID="counter1" STYLE="position:relative; left:10px" TYPE="button" VALUE="Click Me in IE 5.x">
<input type="text" name="b">
<input type="text" name="c">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
var obj = document.getElementById('counter1');

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

document.getElementById('counter1').attachEvent("onclick", firstClick);
obj.setAttribute('onclick','from onclick setAttribute')
document.getElementById('counter1').attachEvent("onclick", secondClick);
obj.setAttribute('counter1','from counter setAttribute')



function firstClick() {
  alert("first Click");
  document.a.b.value = obj.getAttribute('counter1');

}

function secondClick(x)
{
  if (document.a.b.value != "")
     alert("second click came second");
  else
     alert('second click came first')

  document.a.c.value=obj.getAttribute('onclick');

}

alert('counter1 get ' +obj.getAttribute('counter1'))
alert('onclick get ' + obj.getAttribute('onclick'))
//-->
</SCRIPT>
0
 
ZontarCommented:
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.
0
 
ZontarCommented:
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.
0
 
damdamdeoCommented:
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 !!!
0
 
damdamdeoCommented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

  • 4
  • 4
  • 4
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now