Forum Moderators: open
Is it possible to detect which element in a document was clicked without writing the onClick() mehtod with an element?
The issue is that element name would not be available at design time. What I want that if some element is clicked like Text area for writing or a DIV, I can get info that textarea was clicked or some div or whatever. is thee any possibility?
Thanks
does this help...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
.red_text {
color:#600;
}
.green_text {
color:#060;
}
.blue_text {
color:#006;
}
</style><script type="text/javascript">
window.onload=function() {
els=document.body.getElementsByTagName('*');
for(c=0;c<els.length;c++){
els[c].onclick=function(){
getOnClicks(this.tagName,this.id,this.className);
}
}
}
function getOnClicks(el,id,cl) {if(id==''){
id='it has no id set';
}if(cl==''){
cl='it has no class set';
}alert('The element clicked was a...<'+el+'>'+
'\n\nIt\'s id is..."'+id+'"'+
'\n\nIt\'s class name is..."'+cl+'"');}
</script></head>
<body><h1 id="header" class="red_text">header</h1>
<div id="foo" class="green_text">some text</div>
<div class="blue_text">some more text</div>
<div id="image_container"><img id="my_image" src="my_image.gif" alt="my_image"/></div>
</body>
</html>
birdbrain
Here's an example that uses the Yahoo UI Library's Event Utility (makes it much easier to work with events cross-browser). Note, the zoom: 1 is simply to fix IE (it doesn't see the undersides of these boxes as being the correct element unless you give them hasLayout).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<style type="text/css">
#level1 {
border: 1px solid #00f; background-color: #eef; padding: 40px; zoom: 1;
}
#level2 {
border: 1px solid #0f0; background-color: #efe; padding: 40px; zoom: 1;
}
#level3 {
border: 1px solid #f00; background-color: #fee; padding: 40px; zoom: 1;
}
</style>
<title></title>
<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
YAHOO.util.Event.on(window, 'load', function() {
// Attach event handler to body
YAHOO.util.Event.on( document.getElementsByTagName('body')[0], 'click', function(e) {
// Get the element that was the target of the click
var el = YAHOO.util.Event.getTarget(e);
alert(el.id);
});
});
</script>
</head>
<body>
<div id="level1">
<div id="level2">
<div id="level3">
Click Somewhere
</div>
</div>
</div>
</body>
</html>
[edited by: engine at 7:29 am (utc) on Aug. 24, 2007]
[edit reason] fixed sidescroll [/edit]