apatik apatik - 3 months ago 37
CSS Question

Transition effect on a :after element with JQuery toggleclass

I'm using toggleClass to add a class

.expend
to a div
#menu
which expend the height of the menu from 100 to 200px, with a smooth transition (in and out).

I also have an element
#menu:after
for design purposes.

My problem is that when the class
.expend
is toggled and my :after element appears, ther is no fade in (nor fade out) animation.

I'm looking for a clean way to add the same transition animation effect that my menu has to my pseudo-element after has. How can I do that ?



$('#link').click( function() {
$("#menu").toggleClass("expend");
$('.input-area').fadeToggle(300);
} );

#menu {
width: 200px;
height: 100px;
border: 1px solid blue;
padding: 10px;
margin: 10px;
transition: 0.3s ease-out;
}

#menu.expend {
height: 200px !important;
}

#menu.expend:after {
content: 'how to get a 0.3 transition effect here (fade in and fade out) ?';
position: absolute;
top: 170px;
left: 30px;
width: 170px;
height: 60px;
border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="#">click me</a>
<div id="menu">
<div class="input-area">
<input type="text" name="test" id="test" value=""/>
</div>
</div>




Answer

you should set a CSS transition on the pseudo for #menu:after & #menu.expend:after since generated content is not part of the DOM, javascript cannot reach it :)

$('#link').click( function() {
		$("#menu").toggleClass("expend");
		$('.input-area').fadeToggle(300);
	} );
#menu {
  width: 200px;
  height: 100px;
  border: 1px solid blue;
  padding: 10px;
  margin: 10px;
  transition: 0.25s ease-out;
}

#menu.expend {
  height: 200px !important;
}
/* set values of your own , idem for transition timing :) */
#menu:after {
  content: '';
  position: absolute;
  top: 100px;
  left: 30px;
  width: 170px;
  height: 0px;
  border: 0px solid red;
  transition:height 0.3s, top 0.3s, border 0.25s ;
  overflow:hidden;
}
#menu.expend:after {
  content: 'how to get a 0.3 transition effect here (fade in and fade out) ?';
  position: absolute;
  top: 170px;
  left: 30px;
  width: 170px;
  height: 60px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="#">click me</a>
<div id="menu">
  <div class="input-area">
    <input type="text" name="test" id="test" value=""/>
  </div>
</div>

Comments