Simplify multiple jQuery click functions How can I simplify this jQuery code? I feel like I should be able to do this with one click function.

jQuery

$('.btn').eq(0).click(function () { $('.carousel').css({ 'left': '0%' }); });
$('.btn').eq(1).click(function () { $('.carousel').css({ 'left': '-100%' }); });
$('.btn').eq(2).click(function () { $('.carousel').css({ 'left': '-200%' }); });
$('.btn').eq(3).click(function () { $('.carousel').css({ 'left': '-300%' }); });


HTML

&lt;ul&gt;
&lt;li&gt;&lt;a href="" class="btn"&gt;Button 1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="" class="btn"&gt;Button 2&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="" class="btn"&gt;Button 3&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="" class="btn"&gt;Button 4&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
You are correct, you can have one function binding click events to all of your .btn elements.
Working Fiddle Example:
$('.btn').bind(&quot;click&quot;, function(event) {
  event.preventDefault();
  var index = $(this).parent().index();
  $('.carousel').css({ 'left': '-' + (index*100) + '%' });
});

jQuery documentation about index().
Describing what's being suggested:

Bind the click to the .btn class and within the click event you ascertain the index position:
I've opted to use bind() since it's performance efficient when compared with click().
Another reason is the fact that all your elements share the same class, so, you only need to bind a click event to the class instead of attaching a click handler to each .btn.

Use the index and multiply it by 100 as to get the desired left value:
This way you can easily ascertain the correct value since you have a direct relation between the anchor's parent index and the desired left value.

Using event.preventDefault(); to prevent the browser from following the href:
With this, you tell the browser to leave the href attribute alone, thus preventing it to bubble up.

Safe to use the minus signal all the time, since 0 and -0 is the same thing.



In order to further improve the function, and if using the lastest jQuery, I would give an id to the ul element, thus losing the .btn class, having the click event binded to a single DOM element thru delegation:
$('#myUL').on(&quot;click&quot;, &quot;a&quot;, function(event) {
  event.preventDefault();
  var index = $(this).parent().index();
  $('.carousel').css({ 'left': '-' + (index*100) + '%' });
});

jQuery documentation about on().
Useful reading: Why use jQuery on() instead of click().