Anna Riekic
Anna Riekic

Reputation: 738

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'});
});

Upvotes: 3

Views: 197

Answers (4)

Sampson
Sampson

Reputation: 268344

This starts out by selecting all anchors who have a class that begins with Btn. It then binds to all of them an anonymous function that determines the number of pixels #pstrip will be shifted.

$("a[class^=Btn]").on("click", function(){
  var n = -730 * ( this.className.match(/\d+/) - 1 );
  $("#pstrip").animate({ left: n + 'px' });
});

This will work with any number of anchors.

Demo: http://jsbin.com/ovibun/5/edit
Performance: http://jsperf.com/five-buttons/3

enter image description here

Upvotes: 2

dtbarne
dtbarne

Reputation: 8200

A bit more efficient on load, as it only makes one call to .click():

$("#button_container a").click(function() {
    $("#pstrip").animate({left: ($(this).attr("class").match(/Btn([0-9]+)/)[1] * -730) + "px"});
});

This has the added benefit of being able to add more buttons without having to modify the javascript.

Upvotes: 2

josh.trow
josh.trow

Reputation: 4901

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

Upvotes: 4

Imp
Imp

Reputation: 8609

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.

Upvotes: 2

Related Questions