Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better, cleaner way to write this jQuery code

I currently have this written but the title says is there a better way to write/optimize this code?

var p = $('#pstrip');

$('a.Btn1').click(function() {
    p.animate({left: '0px'});
});
$('a.Btn2').click(function() {
    p.animate({left: '-730px'});
});
$('a.Btn3').click(function() {
    p.animate({left: '-1460px'});
});
$('a.Btn4').click(function() {
    p.animate({left: '-2190px'});
});
$('a.Btn5').click(function() {
    p.animate({left: '-2920px'});
});
like image 631
Anna Riekic Avatar asked Feb 18 '26 01:02

Anna Riekic


2 Answers

If all you want to do is shorten it, something like this could work.

$.each([1,2,3,4,5], function(idx, el) {
    var ix = idx;
    $('a.Btn' + el).click(function() {
        p.animate({left: (-730*ix) + 'px'});
    });
})

EDIT: Oops, the parameters were backwards.
EDIT 2: As Imp noted below we need to make sure it calls correctly - I just did a different way

like image 133
josh.trow Avatar answered Feb 19 '26 16:02

josh.trow


var p = $('#pstrip');
var coords = [0, -730, -1460, -2190, -2920];

for (var i = 0; i < 5; i++)
    $('a.Btn' + (i + 1)).click((function(index) {
        return function() {
            p.animate({left: coords[index]});
        }
    })(i));

I put the coordinates into array and cycled through the a.Btn elements, so that (i+1)-th element is associated with the i-th coordinate. The function that is to be bound to the click event is not specified directly, but instead returned by an immediately invoked function expression. The reason is that if I just plainly wrote

.click(function() { p.animate({left: coords[i]}); })

then all callback functions would refer to the same i in closure, which would have value 5 at the time.

like image 21
Imp Avatar answered Feb 19 '26 16:02

Imp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!