GSAP Javascript if else statement woes

594 Views Asked by At

I'm building a basic online banking app with HTML, CSS, and JS.

So far I have the recent transaction screen and a simple animation for opening each individual transaction's description.

I used GSAP to create the animation, and jQuery for handling elements.

However, I have run into a problem getting the description window to close after it has been opened.

CODEPEN HERE, and here is the JS:

$(document).ready(function() {
  $('.list li').click(function() {

    var i = $(this).find('i');
    var li = $(this);
    var desc = $(this).next();
    var tl = new TimelineMax({paused:false});
    var open = false;

    if (open === true) {
      tl.to(i, .3, {rotation: 0})
        .to(li, .3, {borderBottom: 'none', delay: -.2})
        .to(desc, .3, {height: '0', padding: '0', delay: -.2});
      open = false;
    } else {
      tl.to(i, .3, {rotation: 90})
        .to(li, .3, {borderBottom: '2px solid #95a5a6', delay: -.2})
        .to(desc, .3, {height: '55px', padding: '5px', delay: -.2});
      open = true;
    }


  });


});

I use an if statement to decide which animation to play depending on if the description window is open or closed.

I am a designer learning to code, I will take any advice I can get.

1

There are 1 best solutions below

2
On BEST ANSWER

You have the right idea, but var open = false; is in the wrong scope. The way it's written, open is defined as false every time the click handler is called, You want to put it in the parent scope: outside the click handler, before the click handler is ever called.

EDIT since you want to track the "open" state of each element, you need to create a closure for each element. You can do that using .each().

You can do this:

$(document).ready(function() {

  $('.list li').each(function() {

     var open = false;  // <-- Put "open" here

     $(this).click(function() {

        var i = $(this).find('i');
        var li = $(this);
        var desc = $(this).next();
        var tl = new TimelineMax({paused:false});
        // get rid of "open" here

       if (open === true) {
          tl.to(i, .3, {rotation: 0})
            .to(li, .3, {borderBottom: 'none', delay: -.2})
            .to(desc, .3, {height: '0', padding: '0', delay: -.2});
           open = false;
        } else {
           tl.to(i, .3, {rotation: 90})
             .to(li, .3, {borderBottom: '2px solid #95a5a6', delay: -.2})
             .to(desc, .3, {height: '55px', padding: '5px', delay: -.2});
           open = true;
        }


      });


    });
});