Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mouseenter is triggering twice for one enter

I want to do something when the div #demo is hover, so I use the mouseenter event because I don’t want it to bubble. There is one nested/child element inside it which is #test.

However, the problem is that when I slowly enter the #demo from its bottom ( like border ) to the #test element, I don’t know why it triger the mouseenter event twice.

Why does it behave this way? I only want it to trigger the mouseenter one time once it is entered.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the code:

const main = document.querySelector('#demo');

main.addEventListener ( 'mouseenter', function (e) {
    this.style.borderStyle = 'none';

    console.log ( 'enter' );
});
#demo {
  border: 1px solid gray;
  height: 60px;
  padding: 18px;
}

#test {
  background-color: blue;
  height: 100%;
  width: 100%;
}
<div id="demo">
    <div id="test"></div>
</div>

>Solution :

Use this.style.borderColor = 'transparent'; instead.

If use borderStyle = 'none' the height of element was changed, so the mouse will leave element for a very short moment, then mouse keep moving and enter second times.

const main1 = document.querySelector('#demo1');
main1.addEventListener('mouseenter', function(e) {
  this.style.borderStyle = 'none';
  console.log('enter');
});

const main2 = document.querySelector('#demo2');
main2.addEventListener('mouseenter', function(e) {
  this.style.borderColor = 'transparent';
  console.log('enter');
});
#demo1,
#demo2 {
  width: 50%;
  margin: 50px auto;
  background: navy;
  border: 5px solid gray;
  padding: 18px;
}

#demo1 {
  margin-bottom: 100px;
}
<div id="demo1">
  <div id="test1">demo1: border-style</div>
</div>
<div id="demo2">
  <div id="test2">demo2: border-color</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading