soldier soldier - 2 months ago 18
Javascript Question

Transition jQuery addClass and removeClass

I'm trying to achieve an overlay on divs when i hover them.
Basically i'm adding a class on mouseover and removing the class on mouseleave.
The problem is that i cannot make a transition since the main effect of the class belongs to the :after pseudo element.
I'm actually targeting the div with a placeholderclass called .img-target

CSS

.img-overlay{
height: 100%
width: 100%
transition: all 1s ease;
}

.img-overlay::after{
content:"";
display: block;
height: 100%;
position: absolute;
top: 0;
left: 0;
width: 100%;
background-color: rgba(0, 0, 0, .3);
transition: all 1s ease;
}


jQuery

$(window).ready(function() {

$(".img-target").mouseover(function() {
$(this).addClass('img-overlay',1000);

});

$(".img-target").mouseleave(function() {
$(this).removeClass("img-overlay");

});
});


I've already tried to apply a transition to the :after and to the .img-target but nothing seems to be working.
Any ideas? :)

P.S. unfortunately using after pseudo element is actually the only way to overlay the div becouse of the theme structure.

Answer

Your problem is the :after pseudo element does not have an initial state

$(window).ready(function() {
  $(".img-target").mouseover(function() {
    $(this).addClass('img-overlay', 1000);

  });

  $(".img-target").mouseleave(function() {
    $(this).removeClass("img-overlay");

  });
});
.img-target {
  position: relative;
  background-color: gold;
  height: 50px;
  width: 50px;
  transition: all 1s ease;
}
.img-target::after {
  content: "";
  display: block;
  transition: all 1s ease;
}
.img-overlay::after {
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, .3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="img-target"></div>

if you are only using jQuery for the mouse in and our detection you can use CSS instead .img-target:hover::after {...}:

.img-target {
  position: relative;
  background-color: gold;
  height: 50px;
  width: 50px;
  transition: all 1s ease;
}
.img-target::after {
  content: "";
  display: block;
  transition: all 1s ease;
}
.img-target:hover::after {
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, .3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="img-target"></div>

Comments