Search code examples
javascriptjqueryanimationgsap

Floating Input Labels Using GreenSock (GSAP)


I'm trying to create floating input labels using GreenSock. I want to be able to keep the labels at the top if the input field has a value, if not then return label back in place.

Right now the the animation only runs one time and on just one input element. Need help figuring out how I can do this for each input.

// SETUP
const tl = new TimelineMax();
const container = $(".input-container");

// CLICK EVENT
container.on("click", function() {

  // VARIABLES
  const label = $(this).find(".label");


  // TWEEN
  tl.to(label, 0.35, {left: "5", top: "1", transform: "scale(.75)", color: "#333"});  

});

// FOCUSOUT EVENT
container.on("focusout", function() {

  const input = $(this).find(".input");
  if (input.val() === "") {
    tl.reverse();
  }

});

Heres what I have so far: [Demo Link]1


Solution

  • The problem is, that you're using the same TimelineMax object for all of the labels. Each input/container will need its own Timeline.

    You could perhaps attach the Timeline instance directly to the DOM like this:

    // SETUP
    const container = $(".input-container");
    
    // CLICK EVENT
    container.on("click", function() {
    
      // VARIABLES
      const label = $(this).find(".label");
    
      this.tl = new TimelineMax();
      // TWEEN
      this.tl.to(label, 0.35, {left: "5", top: "1", transform: "scale(.75)", color: "#333"});  
    
    });
    
    // FOCUSOUT EVENT
    container.on("focusout", function() {
    
      const input = $(this).find(".input");
      if (input.val() === "") {
        this.tl.reverse();
      }
    
    });
    

    Updated CodePen