Solved

Attaching events using the DOM

Posted on 2003-11-01
20
1,625 Views
Last Modified: 2013-11-19
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
Comment
Question by:JontyDunne
  • 4
  • 4
  • 4
  • +4
20 Comments
 
LVL 10

Expert Comment

by:NetGroove
ID: 9663761
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
 
LVL 10

Expert Comment

by:NetGroove
ID: 9663763
Oh, both methods have the name: anonymous functions.

0
 

Author Comment

by:JontyDunne
ID: 9663785
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
 
LVL 10

Expert Comment

by:NetGroove
ID: 9663826
Like this:

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




0
 
LVL 7

Expert Comment

by:Xxavier
ID: 9663879

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
 
LVL 7

Expert Comment

by:Xxavier
ID: 9663904
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
 

Author Comment

by:JontyDunne
ID: 9663917
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
 
LVL 7

Accepted Solution

by:
Xxavier earned 300 total points
ID: 9663941
Basically I have

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

I am hard pushed to make it neater than that
0
 

Author Comment

by:JontyDunne
ID: 9663953
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
 
LVL 7

Expert Comment

by:Xxavier
ID: 9663979
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:JontyDunne
ID: 9663991
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
 
LVL 25

Expert Comment

by:devic
ID: 9664005
>>>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
 
LVL 10

Expert Comment

by:NetGroove
ID: 9664030
Does this also not work for you:

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


0
 
LVL 15

Expert Comment

by:VincentPuglia
ID: 9664362
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
 
LVL 11

Assisted Solution

by:Zontar
Zontar earned 100 total points
ID: 9664813
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
 
LVL 15

Assisted Solution

by:VincentPuglia
VincentPuglia earned 100 total points
ID: 9664821
<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
 
LVL 11

Expert Comment

by:Zontar
ID: 9664845
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
 
LVL 11

Expert Comment

by:Zontar
ID: 9664937
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
 

Expert Comment

by:damdamdeo
ID: 12841315
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
 

Expert Comment

by:damdamdeo
ID: 12841395
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

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now