PDA

View Full Version : How to get the target element when clicked??



shachi
08-30-2006, 04:24 PM
Hello all,
Can anyone tell me how do I find out which element was clicked?? Do I use something like e.target || e.srcElement ??

Any help would be greatly appreciated.
Thanks.

Twey
08-30-2006, 05:38 PM
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;

jscheuer1
08-31-2006, 06:38 AM
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;

Could you use that in a complete sentence? I tried:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function getEl(){
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;
alert(origEl.tagName);
}
</script>
</head>
<body>
<span onclick="getEl();">Hey!</span>
</body>
</html>

That didn't work too well (it was good in IE and Opera, not FF), this worked out OK in all three:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function getEl(ev){
origEl = ev.target || ev.srcElement;
alert(origEl.tagName);
}
</script>
</head>
<body>
<span onclick="getEl(event);">Hey!</span>
</body>
</html>

vikasbhagwagar
08-31-2006, 10:47 AM
document.onclick = myClickListener;

function myClickListener(e)
{
var eventIsFiredFromElement;
if(e==null)
{
// I.E.
eventIsFiredFromElement = event.srcElement;
}
else
{
// Firefox
eventIsFiredFromElement = e.target;
}
alert("Event is fired from element : " + eventIsFiredFromElement);
// alerts [object]
//... now you can get/set any property on object eventIsFiredFromElement.name or eventIsFiredFromElement.tagName :))
}

jscheuer1
08-31-2006, 11:51 AM
Oh, I get it now:


<script type="text/javascript">
function getEl(){
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;
alert(origEl.tagName);
}
document.onclick = getEl;
</script>

Twey
08-31-2006, 01:34 PM
Yes, it works in an event handler. :)

shachi
08-31-2006, 05:45 PM
Thanks Twey,jscheuer1 and vikasbhagwar!!! Thank you all very much.:)