Reputation: 11
Please help in the implementation of the following problem. Need to perform a click on a particular element, but with an offset.
If i use a standard click - element.click(), then click occurs in the upper left corner of the element:
But i need to do click here:
Can I perform a click on an element + offset? Something like this -
element.click().offset('top: 32, left: 32')
p.s. Ssory for my english.
Upvotes: 1
Views: 6494
Reputation: 3279
element.click()
and assume you are using jQuery. What you want is not possible with jQuery, it can't set offset parameters to the event, you have to use native javascript.clientX / clientY
and pageX / pageY
. Both describe the position of the mousepointer when the click occurs.clientX: 0, clientY: 0
so it occurs in the upper left corner of the document, not of the element.clientX / clientY
to the position of the element relative to the document. You find elements position with .getBoundingClientRect()
..left / .top
are the coordinates of elements topLeft corner. Using them inside the event clicks on its topLeft corner.width / height
of the element. If you add the half of them to x, y
you get coordinates of elements center. Using that in the event performs a click at its center.function clickOnElem(elem, offsetX, offsetY) {
var rect = elem.getBoundingClientRect(),
posX = rect.left, posY = rect.top; // get elems coordinates
// calculate position of click
if (typeof offsetX == 'number') posX += offsetX;
else if (offsetX == 'center') {
posX += rect.width / 2;
if (offsetY == null) posY += rect.height / 2;
}
if (typeof offsetY == 'number') posY += offsetY;
// create event-object with calculated position
var evt = new MouseEvent('click', {bubbles: true, clientX: posX, clientY: posY});
elem.dispatchEvent(evt); // trigger the event on elem
}
You use it as follows;
var el = document.getElementById("myElem");
clickOnElem(el); // clicks on topLeft corner
clickOnElem(el, 'center'); // clicks on elements center
clickOnElem(el, 30, 40); // clicks inside element, 30px from left and 40px from top
Upvotes: 3
Reputation: 1112
This is the best way to do it:
function func(){
alert("Circle clicked!")
}
div{
border-radius: 100000px;
width: 100px;
height: 100px;
background-color: red;
cursor: pointer;
}
<div onClick="func()"></div>
Upvotes: 2