Petar Vasilev
Petar Vasilev

Reputation: 4735

Hiding and showing elements with jQuery flickers in Chrome and Edge

I am trying to make a simple animation with jQuery which works absolutely fine in Firefox but it flickers in Chrome and Edge, here is a jsfiddle, and here is the code:

HTML

<div id="boxes-wrapper">
  <div class="box"></div><div class="box"></div><div class="box"></div>
</div>

CSS

.box {
  width: 150px;
  height: 150px;
  display: inline-block;
  margin: 0;
  padding: 0;
  vertical-align: top;
}

.box:first-child {
  background: pink;
}

.box:nth-child(2) {
  background: skyblue;
}

.box:nth-child(3) {
  background: gold;
}

.box.hover {
  position: relative;
  z-index: 20;
}

html, body {
  position: relative;
  width: 100%;
  height: 100%;
}

#shadow {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  background: black;
  opacity: 0.7;
  z-index: 10;
  width: 100%;
  height: 100%;
}

JavaScript

$('.box').hover(function() {
    $(this).addClass('hover');
  $('#shadow').show();
}, function() {
    $(this).removeClass('hover');
  $('#shadow').hide();
});

I've dug up a few questions on SO but none of them answered how to get rid of the flicker.

Upvotes: 1

Views: 516

Answers (1)

Pete
Pete

Reputation: 58422

Ok, the problem is that your overlay is covering the non hovered boxes so it currently needs to disappear in order to hover the others.

The flash is caused by the space between your boxes - as soon as the mouse leaves, the overlay is hidden.

In order to get around this you will need a mixture of css and move the hover for the overlay to the box wrapper (comments in code):

// remove overlay from this:
$('.box').hover(function() {
  $(this).addClass('hover');
}, function() {
  $(this).removeClass('hover');
});

// add this:
$('#boxes-wrapper').hover(function() {
  $('#shadow').show();
}, function() {
  $('#shadow').hide();
});
html,
body {
  position: relative;
  width: 100%;
  height: 100%;
}
#boxes-wrapper {
  float: left;
  /*this makes the wrapper the same width as the boxes, you may need to add a clear fix after this*/
}
.box {
  width: 150px;
  height: 150px;
  display: inline-block;
  margin: 0;
  padding: 0;
  vertical-align: top;
}
.box:first-child {
  background: pink;
}
.box:nth-child(2) {
  background: skyblue;
}
.box:nth-child(3) {
  background: gold;
}
.box.hover {
  position: relative;
  z-index: 20;
}
#shadow {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  background: black;
  opacity: 0.7;
  z-index: 10;
  width: 100%;
  height: 100%;
  /* add the following - means that the mouse hover will "go through" the overlay */
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes-wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

<div id="shadow"></div>

Upvotes: 2

Related Questions