In a Svelte app I’m trying to detect when the user is hovering over a link, within a div. I’ve added a mouseover event listener to the div, and am checking if the element is a link, but this is too simplistic: it doesn’t detect links that contain HTML tags.
Example code, also available as REPL:
<script>
import { onMount } from 'svelte';
let container;
onMount(() => {
container.addEventListener('mouseover', async (event) => {
if (event.target.tagName !== 'A') return;
console.log(event.target.attributes['href'].value);
});
});
</script>
<div bind:this={container}>
<a href="https://www.example.com">Hello World</a>
<a href="https://www.example.com"><strong>Hello World</strong></a>
</div>
The problem is that second link: hovering over it the target is the strong tag, not the a tag. So, how can I reliably detect all links within the container div, without having to add an event listener to every individual link?
>Solution :
From the target, use .closest('a') to navigate to the enclosing <a> element, if any. (If the element that the event was dispatched to is an <a>, it’ll be returned.)
container.addEventListener('mouseover', (event) => {
const a = event.target.closest('a');
if (a) console.log(a.href);
});
container.addEventListener('mouseover', (event) => {
const a = event.target.closest('a');
if (a) console.log(a.href);
});
<div id="container">
<a href="https://www.example.com">Hello World</a>
<a href="https://www.example.com"><strong>Hello World</strong></a>
</div>