Home > database >  mouseenter/mouseleave, a div, and some text in it
mouseenter/mouseleave, a div, and some text in it

Time:10-26

I have this blue div which shows some text on hover. As soon as you hover the text in it, the text starts blinking. Is there any way to avoid this blinking?

https://jsfiddle.net/pdqcoks7

HTML:

<div ></div>
<div >This text should not<br>blink on hover</div>

CSS:

.lightblue{
  width:50%;
  background:lightblue;
  float:right;
  height:50vh;
}
.text{
  display:none;
  color:#000;
  position:absolute;
  text-align:right;
  top:25px;
  right:25px;
  font-size:24px;
 
}

JQUERY:

$('.lightblue').mouseenter(
            function() {
                $('.text').fadeIn(200) 
            }),

  $('.lightblue').mouseleave(
            function() {
                $('.text').fadeOut(200);
            });

CodePudding user response:

Your text is not a child element of lightblue - so when you render your text on top of the blue box, the mouse is now hovering over the text and not hovering over the blue - so you get mouseleave on the blue.

One option, depending on your requirements, is to move pointer-events from the text - this way the text does not get mouseenter so the blue does not get mouseleave, and everything works fine

$('.lightblue').mouseenter(
    function() {
      $('.text').fadeIn(200)
    })
  .mouseleave(
    function() {
      $('.text').fadeOut(200);
    });
.lightblue{
  width:100px;
  background:lightblue;
    float:right;
  height:50vh;
}
.text{
  display:none;
  color:#000;
  position:absolute;
  text-align:right;
  top:25px;
  right:25px;
  font-size:24px;
  
  /* don't react to mouse move */
  pointer-events:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<div >This text should not<br>blink on hover</div>

You could move the text to inside blue (rearrange the HTML, not reposition), then the mouse events bubble up and, when the text is displayed it's now over the text, and due to the hierarchy is also still over the blue box.

This works fine if the text is fully contained within the blue box.

However as the text is position:absolute, it may appear outside the box - you had the blue box 50% so if the window is small, the text will appear outside the box - this means if you move the mouse outside the blue, but still over the text, it won't disappear.

$('.lightblue').mouseenter(
    function() {
      $('.text').fadeIn(200)
    })
  .mouseleave(
    function() {
      $('.text').fadeOut(200);
    });
.lightblue {
  width: 100px;
  background: lightblue;
  float: right;
  height: 50vh;
}

.text {
  display: none;
  color: #000;
  position: absolute;
  text-align: right;
  top: 25px;
  right: 25px;
  font-size: 24px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >This text should not<br>blink on hover</div>
</div>

  • Related