views:

1137

answers:

1

Hi,

how can simulate an onclick event on a DIV passing only X,Y coordinates???

If I try to make that obviously the dispatchEvent function wants the object on which the event will be raised...but then what is the meaning of passing in event creation the coordinates????

Thanks

+1  A: 

The clientX and clientY parameters are the position relative to the element handling the event, so you need to know what element the click event is going to.

If you want to simulate a click to an unknown element based on window coordinates, you will need to find the element at that position. In IE and Firefox 3, you can use document.elementFromPoint(x, y). I don't know of any way in other browsers, except looping through the elements in the page, looking at their position/size to determine what's at the coordinates.

Your code would look kind of like this:

function simulateClick(x, y) {
    var el = getElementFromPoint(x, y);

    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
        1, 0, 0,
        calculateClientX(el, x), calculateClientY(el, y),
        false, false, false, false, 0, null);

    el.dispatchEvent(evt);
}

getElementFromPoint would use either document.elementFromPoint or iterate over all the elements. calculateClientX/Y would calculate the click coordinates relative to the element.

Matthew Crumley
Great it works very well. Thank you very much!!!!
xdevel2000