title: Multiple instances of a jquery slider on one page
body: <p>I wrote a pretty simple slider using jQuery. It works by counting and numbering the child img elements and displaying the img that corresponds with a counter variable that increases as a user presses the "right" button and decreases if the "left" button is pressed. It works fine unless there are multiple instances of it on a page.(I think because the variables are global)</p>
  
  <p>One button ends up controlling the flow of all of the sliders. Additionally, only one slider will show an image at a time because they all refer back to the same variables.</p>
  
  <p><strong>Is there a way to make each instance of the slider have its own counter ($n) and slide number ($slides) variables?</strong></p>
  
  <p>Here's a jfiddle with what I have: <a href="http://jsfiddle.net/Mn4jk/2/" rel="nofollow">http://jsfiddle.net/Mn4jk/2/</a> (although no actual images)</p>
  
  <p>And here is the direct html and jQuery</p>
  
  <p>html:</p>
  
  <pre><code>&lt;div&gt;
  &lt;img src="../graphics/arrow_left.png" class="left" alt="left"&gt;
  &lt;img src="../graphics/arrow_right.png" class="right" alt="right"&gt;
  &lt;div class="carousel"&gt;
      &lt;img src="../graphics/img1.png" alt="1"&gt;
      &lt;img src="../graphics/img2.png" alt="2"&gt;
      &lt;img src="../graphics/img3.png" alt="3"&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>jQuery:</p>
  
  <pre><code>$(window).ready(function () {
  
  var $n = 0;
  var $slides = $('.carousel img').length - 1;
  
  $('.right').click(function () {
      if ($n &lt;= ($slides - 1)) {
          $('.carousel img').eq($n).fadeOut('400');
          $n++;
          $('.carousel img').eq($n).delay('400').fadeIn('400');
      } else {
          $('.carousel img').eq($slides).fadeOut('400');
          $n = 0;
          $('.carousel img').eq(0).delay('400').fadeIn('400');
      }
  });
  
  $('.left').click(function () {
      if ($n &gt;= 1) {
          $('.carousel img').eq($n).fadeOut('400');
          $n--;
          $('.carousel img').delay('400').eq($n).fadeIn('400');
      } else {
          $('.carousel img').eq(0).fadeOut('400');
          $n = ($slides)
      }
      $('.carousel img').delay('400').eq($n).fadeIn('400');
  });
  
  $('.carousel img').eq($n).fadeIn('400');
  });
  </code></pre>
  
  <p>I know I could just copy the code and make a new class, but I'd rather a solution that would allow for any number of sliders to be used on one page.</p>