This return function is very helpful. I got it working perfectly: https://codepen.io/wildeweg/pen/powKYEM
But when a timeline is defined within a function, I can't get it to work (sorry, this has probably to do with my limited knowledge of javascript.). Probably somebody can give me some pointers, though?
I am doing this:
gsap.utils.toArray(".book").forEach((book) => {
var bookImageSRC = book.querySelector("img").src;
var bookImageNaturalHeight = book.querySelector("img").naturalHeight;
var bookImageNaturalWidth = book.querySelector("img").naturalWidth;
var bookImageProportion = bookImageNaturalWidth / bookImageNaturalHeight;
var bookImageTargetWidth = 200;
var bookImageTargetHeight = bookImageTargetWidth / bookImageProportion;
function bookHover(e) {
if (e.type === "mouseenter") {
var tl_bookIn = gsap.timeline();
tl_bookIn.set(bookImageWrapper, {backgroundImage: "url('" + bookImageSRC + "'", backgroundSize: bookImageTargetWidth + "px " + bookImageTargetHeight + "px", width: bookImageTargetWidth*0.9, height: bookImageTargetHeight*0.9});
tl_bookIn.set(book, {backgroundColor: "#FF89E4"});
tl_bookIn.to(bookImageWrapper, {autoAlpha: 1, rotate: 10, backgroundSize: bookImageTargetWidth + "px " + bookImageTargetHeight + "px", width: bookImageTargetWidth, height: bookImageTargetHeight, duration: 1.6});
} else if (e.type === "mouseleave") {
var tl_bookOut = gsap.timeline();
tl_bookOut.set(book, {backgroundColor: "#F2FF74"});
tl_bookOut.to(bookImageWrapper, {autoAlpha: 0, rotate: 0, backgroundSize: bookImageTargetWidth * 1.2 + "px " + bookImageTargetHeight * 1.2 + "px", width: bookImageTargetWidth*0.6, height: bookImageTargetHeight*0.6, duration: 1});
}
}
book.addEventListener("mouseenter", bookHover);
book.addEventListener("mouseleave", bookHover);
book.addEventListener("mousemove", moveBookImage);
});
Then I try to kill the timeline like this:
return function() {
// other cleanup code can go here.
tl_bookIn.kill();
tl_bookOut.kill();
};
But it says 'Can't find variable: tl_bookIn'. This probably has to do with scope?
Codepen example here:
https://codepen.io/wildeweg/pen/rNwogyM?editors=1010