How, on mousedown
or touchstart
, can I get the position of the mouse relative to or within the container or element it took place in.
So, I know I can get the pageX/Y
or clientX/Y
from the event or on touch, the original event. But that is the positioning compared to the whole viewport. This div is absolute positioned, so how can I get it positioned within the boundaries of its container ( absolute positioned ).
So this works: http://jsfiddle.net/Fb6An/
Here is the code:
$('.dataCard').on('mousedown touchstart', function(event){
$(this).children('.ripple').show().css({'left':event.clientX || event.originalEvent.clientX, 'top':event.clientY || event.originalEvent.clientY});
});
Except it doesn't work in some elements on the full site that I am working on. On elements that are closer to the right edge of the screen, it appears more to the right and lower than the the actual mouse location. In elements to the left, it works fine.
So I was wondering how can I get the position within an element and style the .ripple there?
No need for jQuery when finding the coordinates to set as the style
:
$('.dataCard').on('mousedown touchstart', function(event){
var clickX = (event.clientX || event.originalEvent.clientX),
clickY = (event.clientY || event.originalEvent.clientY);
$(this).children('.ripple').each(function(){
$(this)
.show()
.css({
left: clickX - this.offsetParent.offsetLeft,
top: clickY - this.offsetParent.offsetTop
});
});
});
Updated fiddle from @Gaby aka G. Petrioli: http://jsfiddle.net/s52u4/1/
In this particular case, using jQuery is like hitting a thumbtack with a sledge hammer.