1

I was wondering what is the best way to prevent variables from being global when they need to be used across multiple functions within the same module.

As you can see I need those variables to be available throughout - but I don't necessarily want then to be defined in the global as that would muck things up in the end. Do I wrap them in a function?

Also if anybody has any tips on ways to improve this code I'd love to hear it.

Here's my code example:

// Info Bullet Slide Out

var slideOut,
    clickedButton,
    clickedParent,
    activeClass = 'is-active',
    openClass = 'is-open';

    function closeSlideOut(){
      $('.tlx-img-point').removeClass(activeClass);
      slideOut.removeClass(openClass);
      clickedParent.removeClass(activeClass);
    }

    function openSlideOut(){
      slideOut = $('.' + clickedButton.attr('id'));
      slideOut.addClass(openClass);
      clickedParent.addClass(activeClass);
      clickedButton.addClass(activeClass);
    }

$('.tlx-img-point').on('click', function(){
  clickedButton = $(this);
  clickedParent = clickedButton.parent();

  // If you clicked on the same button twice just close the slideout
  if($(this).hasClass('is-active')){
    closeSlideOut();

  // If you clicked on another info button close this one and open the new one
  }else if(clickedParent.hasClass(activeClass)){
    closeSlideOut();
    // Delay 5ms to allow css animation to complete
    setTimeout(function(){
      openSlideOut();
    }, 650);

  // Open the info slide out
  }else{
    openSlideOut();
  }
});
cookie monster
  • 10,671
  • 4
  • 31
  • 45
MarioD
  • 1,703
  • 1
  • 14
  • 24
  • 2
    Global scope sucks - use an IIFE to wrap everything up! http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – Mister Epic Jul 11 '14 at 18:00
  • Thank you Chris, reading the article now. – MarioD Jul 11 '14 at 18:03
  • 2
    If everything is inside `$(document).ready(function()...)` then it's not in the global scope, it's in the scope of that function. – Barmar Jul 11 '14 at 18:04

1 Answers1

5

Wrap everything into a function:

(function(){

  // all your code

})();

The scope of your variables will be the anonymous, self-calling function wrapper.

moonwave99
  • 21,957
  • 3
  • 43
  • 64