Event Detection of elements at runtime

A

Adnan Siddiqi

Hi
Is it possible to detect event of an element on runtime without
explicitly attaching event by using onClick() etc?.

I have a page which can generate run time DIVs and form elements and I
don't even have their names or Ids for reference. Is it possible in
Javascript to capture which element was clicked and then can refer
that element by returning it's ID or tag type?


Thanks
 
T

Thomas 'PointedEars' Lahn

Adnan said:
Is it possible to detect event of an element on runtime without
explicitly attaching event by using onClick() etc?.

I have a page which can generate run time DIVs and form elements and I
don't even have their names or Ids for reference. Is it possible in
Javascript to capture which element was clicked and then can refer
that element by returning it's ID or tag type?

Yes, through event bubbling[1]. The event has to bubble (`click' does in
the standard DOM and all known proprietary DOMs), and one parent element has
to have an event listener attached for the event. For example:

....
<head>
<meta http-equiv="Content-Script-Type" content="text/javascript"></meta>
<script type="text/css">
// <![CDATA[
function clickHandler(e)
{
if (e)
{
var t = e.target || e.srcElement;
if (t) window.alert(t.id);
}
}
// ]]>
</script>
</head>

<body onclick="clickHandler(event)">
...
<div id="foo">
...
</div>
...
</body>
....

As you can see, once you have the element object reference (t), you don't
need the ID or its element type ("tag name") anymore to refer to it.


HTH

PointedEars
___________
[1] http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-bubbling
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,883
Members
47,414
Latest member
djangoframe

Latest Threads

Top