You are correct, you can have one function binding click
events to all of your .btn
elements.
Working Fiddle Example:
$('.btn').bind("click", 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("click", "a", 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().