Javascript lets you fire custom events when the user hovers over an element or when a user clicks on an element. But how does Javascript know which elements should receive the click event?
For example an HTML element like this:
<div style="width: 300; height: 300;">
<a href="hello">Hello World</a>
</div>
If I click on the link, the browser knows to execute all click events attached to that link. But how does the browser know where on the page the link is (or even that it’s visible?)
Consider:
<div id="mydiv" style="width: 300; height: 300;">
<a href="hello">Hello World</a>
</div>
<style>
#mydiv a {
display: none;
}
</style>
Now nothing will happen when I click on the space where the link used to be visible. How does the browser know not to fire click/hover events in this case? If I wanted to recreate the algorithm used, what elements would I need?
I assume there is some function in browser code that looks like this:
/* Take user's mouse coordinates and return a DOM element. */
function returnElementBasedOnMouseCoordinate(x, y) {
/* Does a lookup function on some data structure */
return someElementInTheDom;
}
How does that function work?
Typically (meaning WebKit :)) browsers create a render tree which roughly corresponds to the document DOM tree but reflects the visual rather than logical structure of the document. For invisible elements (display: none), there are no corresponding render objects which participate in mouse event handling. The render tree is modified every time the DOM or some of its visual aspects (element display, visibility, dimensions, etc.) change.