2

I'm attempting to achieve a particular effect onclick. I've created an angled or razor-blade style div using a parent div-element, and a pseudo-element :after (see snippet below). What I'm trying to make happen is when the user clicks on the parent element, the skew property I have set up, shifts to a different skewed angle.

My problem is what regardless of whether I call the parent or the pseudo, onclick I cannot get the animation to work. Can anyone point me in the right direction?

$(document).ready(function() {
 
 $('.slantedDiv').click(function() {
  $('.slantedDiv .slantedDiv:after').toggleClass('active');
 });
});
* {
 padding: 0;
 margin: 0;
}

.slantedDiv {
 position: relative;
 width: 100%;
 height: 300px;
 background-color: yellow;
}

.slantedDiv:after {
 position: absolute;
 width: 100%;
 height: 100%;
 content: '';
 background: inherit;
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
 transform-origin: top left;
 transform: skewY(10deg);
 transition: all .3s ease-in-out;
}

.active {
 transform-origin: top right;
 transform: skewY(-10deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slantedDiv"></div>
Theodore Steiner
  • 1,553
  • 2
  • 23
  • 34

1 Answers1

4

The issue is to do with the selector in the click handler. Firstly, the element is just .slantedDiv, so repeating the class will not match any elements. You can avoid that issue entirely by just using the this reference in the jQuery object. Secondly, and more importantly, jQuery cannot select pseudo elements so including :after will not find anything.

Instead you need to toggle() the activeclass on the .slantedtDiv directly and then use the :after in your CSS rule based on the presence of the active class, something like this:

$(document).ready(function() {
  $('.slantedDiv').click(function() {
    $(this).toggleClass('active');
  });
});
* {
  padding: 0;
  margin: 0;
}

.slantedDiv {
  position: relative;
  width: 100%;
  height: 300px;
  background-color: yellow;
}

.slantedDiv:after {
  position: absolute;
  width: 100%;
  height: 100%;
  content: '';
  background: inherit;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  transform-origin: top left;
  transform: skewY(10deg);
  transition: all .3s ease-in-out;
}

.slantedDiv.active:after {
  transform-origin: top right;
  transform: skewY(-10deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slantedDiv"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339