Forum Moderators: open
<div id="ha1">...</div>
<div id="hb2">...</div>
<div id="hc3">...</div>
I can not modify the XHTML whatsoever. Strictly from the JavaScript itself how do I detect the ID of the element that is clicked? I'd like to set it to a variable. So for example if I assign the variable to alert, if the user clicks on "hb2" it will set the variable's value to "hb2", alert, and can be repeated. The script needs to be able to reassign the variable's value every time a new ID is detected.
- John
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"><script type="text/javascript">
var unknown;
window.onload=function() {
el=document.body.getElementsByTagName('*');
for(c=0;c<el.length;c++) {
el[c].onclick=function() {
unknown=this.id;
alert(unknown);
}
}
}
</script></head>
<body><div id="ha1">...</div>
<div id="hb2">...</div>
<div id="hc3">...</div></body>
</html>
birdbrain
- John
<?php
header("Content-type: application/xhtml+xml");
echo '<?xml version="1.0" encoding="UTF-8"?>
';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test Case</title>
<script type="text/javascript">
//<![CDATA[var unknown;
window.onload=function() {
el=document.body.getElementsByTagName('*');
for(c=0;c<el.length;c++) {
el[c].onclick=function() {
unknown=this.id;
alert(unknown);
}
}
}
//]]>
</script>
</head><body>
<h1 id="header1">header</h1>
<div id="ha1">...</div>
<div id="hb2">...</div>
<div id="hc3">...</div></body>
</html>
*edited title.
[edited by: JAB_Creations at 7:13 pm (utc) on Sep. 30, 2007]
No problem, John, you're very welcome. ;)
Instead, you could attach a single event handler to your body element, and then examine the target of that event to determine where it came from. Here's an example that uses the Yahoo UI Library's Event utility, but if you didn't want to use the YUI library, you could easily re-write the event handling to your specific needs:
<!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">
<title></title>
</head>
<body>
<h1 id="header1">header</h1>
<div id="ha1">...</div>
<div id="hb2">...</div>
<div id="hc3">...</div>
<div>...</div>
<script type="text/javascript" src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
YAHOO.util.Event.on(window, 'load', function() {
// Attach onclick handler to body
YAHOO.util.Event.on(document.getElementsByTagName('body')[0], 'click', function(e) {
// Get the id of the target for the event
var el = YAHOO.util.Event.getTarget(e);
alert( el.id ¦¦ "no id specified" );
});
});
</script>
</body>
</html>