Jump to content
Search Community

Help me understand where I made a mistake

Koto test
Moderator Tag

Go to solution Solved by Koto,

Recommended Posts

Help me understand where I made a mistake
Hi all. Don't judge harshly, I'm still a newbie and still learning animation using GSAP. But the question still appeared. I want to animate menus for both mobile devices and monitors using media queries, but I encountered the following artifact - when loading a js script with a screen width <768px and when you click on burgerMenu, everything works as it should, headerMenu increases by height up to 100dvh and then the menuItems are drawn and when I click on the burgerMenu again, the menuItems are removed first and then the height of the headerMenu returns to its original height = 4.25rem , but when I increase the screen width >=768px and then return the width back to <768px the headerMenu starts to behave incorrectly since it is expected that when you click on the burgerMenu, the height of the headerMenu increases to 100dvh and immediately returns to 4.25rem and at the same time the menuItems are drawn, which is not the result that I would like to see. Please tell me where I am making a mistake.

78978.JPG

See the Pen rNoJEMM by Abu2002 (@Abu2002) on CodePen

Link to comment
Share on other sites

Hi @Koto welcome to the forum! 

 

I don't have a lot of time right now to dig into everything here, but I wanted to offer you some quick advice about how to get the most out of these forums... try creating a demo that only focuses on the issue at hand, your current demo has 400 lines of Javascript and on top of that another 500 lines of CSS, before anyone can try and dive in to the issue they first have to dissect the code to see what everything does. 

 

Try creating a demo with a view coloured divs and just the bare minimum of Javascript, this will greatly increase your chances for anyone to dive in to your code and find the issue. Hope it helps and happy tweening! 

Link to comment
Share on other sites

33 minutes ago, mvaneijgen said:

Привет@Кото добро пожаловать на форум! 

 

У меня сейчас не так много времени, чтобы вникать во все здесь, но я хотел дать вам несколько быстрых советов о том, как получить максимальную отдачу от этих форумов... попробуйте создать демоверсию, которая фокусируется только на этой проблеме. С другой стороны, ваша текущая демо-версия содержит 400 строк Javascript и, кроме того, еще 500 строк CSS, прежде чем кто-либо сможет попытаться углубиться в проблему, ему сначала нужно проанализировать код, чтобы увидеть, что все делает. 

 

Попробуйте создать демо-версию с цветными элементами div и минимумом Javascript. Это значительно увеличит ваши шансы на то, что кто-нибудь углубится в ваш код и найдет проблему. Надеюсь, это поможет и счастливого подросткового периода! 

Thank you very much for your quick response. I have shortened the code as much as possible to focus on the problem

See the Pen ExGRdVp by Abu2002 (@Abu2002) on CodePen

Link to comment
Share on other sites

Hi,

 

I think the issue lies in the fact that you are removing an event listener on a different add() method in your MatchMedia instance:

mm.add("(max-width: 767px)", () => {
  // This is defined inside this scope
  // Not available outside this add() method's callback
  const handleBurgerMenuClick = () => {
    ...
  };
  burgerMenu.addEventListener("click", handleBurgerMenuClick);
});
mm.add("(min-width: 768px)", () => {
  // Removing event listener
  // but handleBurgerMenuClick is not defined inside this scope
  burgerMenu.removeEventListener("click", handleBurgerMenuClick);
});

GSAP MatchMedia has a cleanup function that is returned in the add method that allows you to do that:

mm.add("(max-width: 767px)", () => {

  return () => { 
    // optionally return a cleanup function that will be called when
    // none of the conditions match anymore (after having matched)
  }
}); 

So in your case it would be like this:

mm.add("(max-width: 767px)", () => {
  // This is defined inside this scope
  // Not available outside this add() method's callback
  const handleBurgerMenuClick = () => {
    ...
  };
  burgerMenu.addEventListener("click", handleBurgerMenuClick);
  
  return () => burgerMenu.removeEventListener("click", handleBurgerMenuClick);
});
mm.add("(min-width: 768px)", () => {
  // Don't care about that event listener here
});

That seems to work in the way you intend:

See the Pen GRPGaPj by GreenSock (@GreenSock) on CodePen

 

Give that a try and let us know how it works. Hopefully this helps.

Happy Tweening!

  • Like 2
Link to comment
Share on other sites

  • Solution
3 hours ago, Rodrigo said:

Hi,

 

I think the issue lies in the fact that you are removing an event listener on a different add() method in your MatchMedia instance:

mm.add("(max-width: 767px)", () => {
  // This is defined inside this scope
  // Not available outside this add() method's callback
  const handleBurgerMenuClick = () => {
    ...
  };
  burgerMenu.addEventListener("click", handleBurgerMenuClick);
});
mm.add("(min-width: 768px)", () => {
  // Removing event listener
  // but handleBurgerMenuClick is not defined inside this scope
  burgerMenu.removeEventListener("click", handleBurgerMenuClick);
});

GSAP MatchMedia has a cleanup function that is returned in the add method that allows you to do that:

mm.add("(max-width: 767px)", () => {

  return () => { 
    // optionally return a cleanup function that will be called when
    // none of the conditions match anymore (after having matched)
  }
}); 

So in your case it would be like this:

mm.add("(max-width: 767px)", () => {
  // This is defined inside this scope
  // Not available outside this add() method's callback
  const handleBurgerMenuClick = () => {
    ...
  };
  burgerMenu.addEventListener("click", handleBurgerMenuClick);
  
  return () => burgerMenu.removeEventListener("click", handleBurgerMenuClick);
});
mm.add("(min-width: 768px)", () => {
  // Don't care about that event listener here
});

That seems to work in the way you intend:

 

 

 

Give that a try and let us know how it works. Hopefully this helps.

Happy Tweening!

Thank you so much for the tip! I was close to this solution since I already realized that I had burgerMenu.addEventListener listeners overlapping one another 🤦‍♂️. Thanks again for the quick response!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...