` only trigger when the pointer enters/leaves the table as a whole. It's impossible to get any information about transitions inside it.
So, let's use `mouseover/mouseout`.
Let's start with simple handlers that highlight the element under mouse:
```js
// let's highlight an element under the pointer
table.onmouseover = function(event) {
let target = event.target;
target.style.background = 'pink';
};
table.onmouseout = function(event) {
let target = event.target;
target.style.background = '';
};
```
```online
Here they are in action. As the mouse travels across the elements of this table, the current one is highlighted:
[codetabs height=480 src="mouseenter-mouseleave-delegation"]
```
In our case we'd like to handle transitions between table cells ``: entering a cell and leaving it. Other transitions, such as inside the cell or outside of any cells, don't interest us. Let's filter them out.
Here's what we can do:
- Remember the currently highlighted ` | ` in a variable, let's call it `currentElem`.
- On `mouseover` -- ignore the event if we're still inside the current ` | `.
- On `mouseout` -- ignore if we didn't leave the current ` | `.
Here's an example of code that accounts for all possible situations:
[js src="mouseenter-mouseleave-delegation-2/script.js"]
Once again, the important features are:
1. It uses event delegation to handle entering/leaving of any ` | ` inside the table. So it relies on `mouseover/out` instead of `mouseenter/leave` that don't bubble and hence allow no delegation.
2. Extra events, such as moving between descendants of ` | ` are filtered out, so that `onEnter/Leave` runs only if the pointer leaves or enters ` | ` as a whole.
```online
Here's the full example with all details:
[codetabs height=460 src="mouseenter-mouseleave-delegation-2"]
Try to move the cursor in and out of table cells and inside them. Fast or slow -- doesn't matter. Only ` | ` as a whole is highlighted, unlike the example before.
```
## Summary
We covered events `mouseover`, `mouseout`, `mousemove`, `mouseenter` and `mouseleave`.
These things are good to note:
- A fast mouse move may skip intermediate elements.
- Events `mouseover/out` and `mouseenter/leave` have an additional property: `relatedTarget`. That's the element that we are coming from/to, complementary to `target`.
Events `mouseover/out` trigger even when we go from the parent element to a child element. The browser assumes that the mouse can be only over one element at one time -- the deepest one.
Events `mouseenter/leave` are different in that aspect: they only trigger when the mouse comes in and out the element as a whole. Also they do not bubble.
|