yaharga yaharga - 1 year ago 120
Javascript Question

How to use JavaScript variable outside if-statement scope between two if-statements when it is declared in one of them?

I have a nav menu that animates when opening and closing. I use the animating object

from GSAP. I only need to create it once the menu is open and then I can use it whenever. Once the menu is closed I'll delete the variable because it's useless. I'd like to avoid declaring it outside the click event as a global variable. Is there a better logical way to do this or should I just stick with declaring a global variable?

$('.dropdown-toggle').on('click', function() {

if ($(this).is('.top-toggler:not(.active)')) { // If main menu dropdown toggler is inactive
// Declare the animating object
var navTimeline = new TimelineLite(new TweenLite($(this).next('.toggleable').children(), 0.75, {margin: '0', transform: 'perspective(320px) rotateX(0deg)', boxShadow: 'inset 0px 0px 20px 0px rgba(0,0,0,0)'}));
$(this).addClass('active'); // Give the button class active
navTimeline.play(); // Open up the menu using the animation

if ($(this).hasClass('active')) { // If it is active
navTimeline.reverse(); // Reverse the animation to close it


Answer Source

You can use jQuery's data() method to save the object to the element's jQuery data cache. You can then remove/null it whenever you need

if ($(this).is('.top-toggler:not(.active)')) {
  var navTimeline = new TimelineLite(...);

if ($(this).hasClass('active')) { 
  var navTimeline = $(this).data("timeline");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download