Reputation: 31
I am wondering if it is possible to attach an onclick event to specific coordinates in a document. Maybe something similiar to "area coords" in an image map that would allow me to create a rectangular or circular area that when clicked on would execute some code. Been trying to find a solution all morning hope someone with better coding knowledge could clarify this for me.
Upvotes: 3
Views: 170
Reputation: 9210
You could attach a click event to the document itself as opposed to any specific element. The event data should contain the coordinates of the mouse at the time of the click (clientX and clientY).
Assuming no other element intercepts and cancels propagation or returns false, the event should bubble up to the document and your data will be there for you.
$(document).click(function(ev){
console.log(ev.clientX, ev.clientY)
})
That will give you the mouse pointer position in the window. If you want it to be relative to the top of the document, you'll need to do some math using the scroll position of the document.
You could also write some code to filter out clicks that do or do not fall within a given set of coordinates.
Upvotes: 3
Reputation: 28124
Short answer: no.
Long answer:
You could probably write a plugin to do this, but I'm just going to explain the functionality.
Basically, you bind to the click event, like usual. Be sure that the element you bind to is reachable.
Then, loop over an array of coordinates, and if the event position fell in any of the coordinates, called the associated event handler.
Edit: If it wasn't obvious, you can replace "a bunch of coordinates" with a function, or more precisely, a mathematical calculation. You could pass an equation to the handler which works with any kind of 2d shape you want.
Upvotes: 1
Reputation: 191749
No, not unless you have an element that occupies these coordinates. Instead, you could bind the event to whatever element occupies that coordinate space and simply check the coordinates of the click in the event object.
Upvotes: 0