typo_
typo_

Reputation: 21

OnMouseEnter code alternative

I have this code snippet originally made by Shomz (special thanks) but lately the solution is messing around (fade in-out effect sometimes is skipping) in Chrome - tested in v45.0.2454.99 m (64-bit) and also v45.0.2454.85 m (64-bit), Win7 64-bit;

var shown = true;
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');

parent.addEventListener('mouseenter', function(){
  child.style.opacity = shown ? 0 : 1;
  shown = !shown;
});
* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
  transition: opacity 0.5s linear;
}


p {
  padding: 1em;
}
<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>

The code should work like we have in this example. At this point, I am interested in your JS/jQuery/CSS code alternatives. Is there any possibility to rewrite the code in order to be functional in latest versions of Chrome too? Thanks.

Upvotes: 0

Views: 649

Answers (2)

pherris
pherris

Reputation: 17703

The event onmouseenter is probably the problem. This event is fired more than you might think when you have nested DOM. There is a great writeup on MDN but the quick solution is to try onmouseover instead.

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

Using jQuery all you need to do is use fadeToggle()

$('.parent').mouseenter(function(){
  $('.child').fadeToggle();
});
* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
}


p {
  padding: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>

Upvotes: 1

Related Questions