function caller invalid element
-
16-06-2021 - |
Question
If I have :
<div id="mydiv" onmouseover="myfunc()">
<div id="mydiv1"></div>
<div id="mydiv2"></div>
</div>
<script>
function myfunc() {
var evt = window.event || arguments.callee.caller.arguments[0];
var em = evt.target || evt.srcElement;
return em.id;
}
</script>
The function is called by mydiv
onmouseover, but if mouse cursor is over mydiv1
function returns mydiv1
.
How to make it always to show mydiv
?
P.S : I know that I can use something like myfunc(this)
, but I would like to find caller from inside my function.
Solution
Personally I would prefer to use jQuery to hook up the event:
$('#mydiv').on('mouseover',function(){
var id = $(this).attr('id');
// ...
});
If this should be applied to several elements, then use a class selector instead:
$('.hoverable').on('mouseover',function(){
var id = $(this).attr('id');
// ...
});
To also handle future content, attach the event handler to a common ancestor, and select the hoverable elements in the second parameter to on
:
$('body').on('mouseover','.hoverable',function(){
var id = $(this).attr('id');
// ...
});
OTHER TIPS
You should attach the event handler via JavaScript. You can then access the element it is directly bound to as this
inside it.
<div id="mydiv">
<div id="mydiv1"></div>
<div id="mydiv2"></div>
</div>
<script>
function myFunc() {
return this.id;
}
var mydiv = document.getElementById('mydiv');
mydiv.onmouseover = myFunc;
</script>
You can do this using Jquery easily.
$('#mydiv').hover(function(){
alert(this.id);
});
Check this : http://jsfiddle.net/shahvj27/6zE96/