Q:

Check when the cursor hovers over a link (Particularly a YouTube link)

I want to display the in console link hovered over when the mouse cursor hovers over a link (In this case YouTube link).
Right now here's what I have.
window.onload = () => {
    var links = document.querySelectorAll('[href*="https://www.youtube.com/watch?v="],[href*="https://youtu.be/"]'); //This will selecet an element with a href that has a link that involve either https://youtu.be/ or https://www.youtube.com/watch?v= in the link (Meaning YouTube video links)
    links.forEach(link => {
        link.addEventListener("mouseenter", () => {
            console.log(`Link: ${link} hovered over.`)
        });
    });
}

How this code works is that when the site has started or reloaded, It's going to check for any element that has a href which has a link that has either https://www.youtube.com/watch?v= or https://youtu.be/ basically a youtube video and then save those links, when one of them i hovered over, It's tell which.
This works fine but one downside that I'm currently facing is that new links that are added in after the site has already started or reloaded won't be counted and therefore when I hover them it won't show the links, I'm refering to comments; for-example if I make a comment that has a link to a video, after i post that comments and hover over that link I posted, It won't show the link. I could make a function which reloads every like 5 seconds but this doesn't seem to be a good idea. Plkus what I'm actually working on, realoding every time won't be good. Anyway of doing this? And I apologise for the long story. :)

A:

Instead of adding the eventlistener to each link, you can add it to a parent element that you know will contain all the links. The event will be passed on (delegated) and you can catch which link was hovered in the event.relatedTarget.
You'd have to use the "mouseover" event instead of "mouseenter" to get the children. Also, the wider the net, the greater the performance hit. So delegate the event to the closest ancestor you can.
Edited to run script when mouse enters the link.

const container = document.querySelector('.container')

container.addEventListener('mouseover', ev => {
  const target = ev.relatedTarget
  if (target && target.tagName === 'A') {
    alert(
      `Link: ${target.getAttribute('href')} hovered over.`)
  }
})

const otherContainer = document.querySelector('.other-container')

otherContainer.addEventListener('mouseover', ev => {
  const target = ev.path[0]
  if (target && target.tagName === 'A') {
    alert(
      `Now it targets when entering ${target.getAttribute('href')}.`)
  }
})
<div class="container">
  <a href="http://example.com" target="_blank">runs when mouse leaves</a>
</div>

<div class="other-container">
  <a href="http://example.com" target="_blank">runs when mouse enters</a>
</div>

