1

In the js code below mouseover event listeners are added to the div elements. This is visualized by a change in the border style.

I am trying to make it so that the mouseover event only fires when the mouse enters from externally, and not when re-entering from one of the child paragraphs.

In other words you can see when moving the cursor from a parent div to one of its children, the cursor is no longer considered over the parent, and when the cursor moves off the child and back onto the parent the mouseover event is called again. I am trying to prevent this event call. Rather it should only trigger when the mouse moves into the div from externally.

side note: I am aware of the :hover css selector but am looking for a javascript solution.

<style>
    div, p {
        margin: 8px;
        padding: 8px;
        display: inline-block;
        border: 1px dashed grey;
    }
</style>
<div>
    <p></p>
    <p></p>
    <p></p>
</div>

<div>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</div>

<script>
    let rootDivs = document.querySelectorAll("body > div");
    for (let rootDiv of rootDivs) {
        rootDiv.addEventListener("mouseover", function(event) {
            if (event.target === rootDiv) {
                event.target.style.borderColor = "green";
                event.target.style.borderStyle = "solid";
            }
        });

        rootDiv.addEventListener("mouseout", function(event) {
            if (event.target === rootDiv) {
                event.target.style.borderColor = "grey";
                event.target.style.borderStyle = "dashed";

            }
        });
    }
</script>
Talha Jutt
  • 56
  • 1
  • 11
SSMSJM
  • 149
  • 6
  • 3
    Use [mouseenter](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event) and [mouseleave](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event) events instead of `mouseover` and `mouseout`. – Teemu Dec 29 '22 at 13:30
  • Thank you! That's what I needed. A great simple solution – SSMSJM Dec 29 '22 at 13:32

0 Answers0