ivan
ivan

Reputation: 11

Clicking on element (with offset)

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:

[image #1]

But i need to do click here:

[image #2]

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

Answers (2)

Martin Ernst
Martin Ernst

Reputation: 3279

  • I see you using 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.
  • A click-event-object has two pairs of parameters inside: clientX / clientY and pageX / pageY. Both describe the position of the mousepointer when the click occurs.
  • The position is relative to the document, not to the element. A standard click has clientX: 0, clientY: 0 so it occurs in the upper left corner of the document, not of the element.
  • If you want to click on an element, you have to set clientX / clientY to the position of the element relative to the document. You find elements position with .getBoundingClientRect().
  • The positions in the Rect .left / .top are the coordinates of elements topLeft corner. Using them inside the event clicks on its topLeft corner.
  • Now you can add an offset to the coordinates. Inside the Rect you find also the 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

Tamás
Tamás

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

Related Questions