Reputation: 205
<script>
$("flexbox.center").scroll(changeClass);
function changeClass() {
if($("#coverphoto").hasClass('.coverphoto')){
$("#coverphoto").removeClass("coverphoto").addClass("newshape");
}
else{
$("#coverphoto").removeClass("newshape").addClass("coverphoto");
}
}
</script>
clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
transition: 0.5s ease-in-out;
-----
clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
transition: 0.5s ease-in-out;
Hello,
my goal is to smoothly change the shape of a clipped image on scroll. My approach was to simply switch between the two css properties on scroll but this does not work. (By the way this works perfectly with :hover on the initial css property)
Any hints are highly appreciated and would mean a lot to me!
Upvotes: 1
Views: 2986
Reputation: 273561
You have error in your code, the hasClass()
function doesn't take a selector but only the class name :
function changeClass() {
if ($("#cover").hasClass('coverphoto')) {
$("#cover").removeClass("coverphoto").addClass("newshape");
} else {
$("#cover").removeClass("newshape").addClass("coverphoto");
}
}
.coverphoto {
clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
transition: 0.5s ease-in-out;
}
.newshape {
clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
transition: 0.5s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cover" class="coverphoto">
<img src="https://lorempixel.com/400/150/">
</div>
<button onClick="changeClass()">change</button>
By the way you can optimize your logic by simply using toggleClass()
:
function changeClass() {
$("#cover").toggleClass("newshape");
}
.coverphoto {
clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
transition: 0.5s ease-in-out;
}
.newshape {
clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cover" class="coverphoto">
<img src="https://lorempixel.com/400/150/">
</div>
<button onClick="changeClass()">change</button>
Here is a trigger on scroll event:
$(document).scroll(function() {
if ($(window).scrollTop() <= 150) {
$("#cover").removeClass("newshape");
} else {
$("#cover").addClass("newshape");
}
});
body {
height: 150vh;
}
.coverphoto {
position: fixed;
clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
transition: 0.5s ease-in-out;
}
.newshape {
clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cover" class="coverphoto">
<img src="https://lorempixel.com/400/150/">
</div>
Upvotes: 1