Given a document such as this:
<body><div class="a"><div class="b"><div class="c"></div></div></div></body>
(in the example everything is a div - but they could be anything)
I want to run a click event handler for the div which was clicked and all its parent's
i.e. if you click on .c
I would expect the event to fire for .c
then .b
then .a
If you click on .b
then the event should fire for .b
then .a
N.B. in this instance I am using $('body').on('click', function(event){...})
using $('div').click(function(event){...})
is not a practical option in my instance for reasons not relevant to the question.
I tried walking the dom tree from within the event handler which works but the event object contains the wrong offsets.
So my question really is - is there a built in way to have the event handler called with the above pattern.
Or failing that - is there a built in way to manipulate offsets the event object given a "from" and "to" element.
i.e. something like AdjustOffsets(event, $target, $target.parent())
Or failing that - what logic do I need in order to perform this manipulation by hand.
On the last case I have this code but it doesn't work.
if ($target.css('position') != 'static' && $target.css('position') != '')
{
event.clientX += $target.css('left');
event.clientY += $target.css('top');
}
event.clientX += $target.css('borderLeftWidth');
event.clientY += $target.css('borderTopWidth');
event.clientX += $target.css('marginLeft');
event.clientY += $target.css('marginTop');
$target = $target.parent();
event.clientX += $target.css('paddingLeft');
event.clientY += $target.css('paddingTop');
This fails because the CSS properties contain units.
The units are easily stripped but I believe some browsers return the original unit here (which could be em
or pt
for example) whereas the clientX
property is required to be pixels - so conversion is necessary.
Also it was a best-guess on my part and probably misses a thousand obscure css3 cases - hence my ambitious desire for some kind of built-in method.