Bart. K Bart. K - 1 year ago 61
jQuery Question

How would I loop this?

I am trying to loop functionality for buttons I've made. I have 3 video collections. and they all need the same script for next and previous.

What I want is that I only have to make one next button and one prev button.
This is what it should do:



$("#next-1").click(function(){
var $this = $(".video-album-1");
callback = function() {
$this.insertBefore($this.siblings(':eq(2)'));
}
$this.fadeOut(200, callback).fadeIn(400);
});

$("#prev-1").click(function(){
var $this = $(".video-album-1");
callback = function() {
$this.insertAfter($this.siblings(':eq(3)'));
}
$this.fadeOut(200, callback).fadeIn(400);
});

$("#next-2").click(function(){
var $this = $(".video-album-2");
callback = function() {
$this.insertBefore($this.siblings(':eq(2)'));
}
$this.fadeOut(200, callback).fadeIn(400);
});

$("#prev-2").click(function(){
var $this = $(".video-album-2");
callback = function() {
$this.insertAfter($this.siblings(':eq(3)'));
}
$this.fadeOut(200, callback).fadeIn(400);
});





I've already tried to loop it, but this doesn't work:



for (i = 0; i < 3; i++) {
$("#next-"+i).click(function(){
var $this = $(".video-album-"+i);
callback = function() {
$this.insertBefore($this.siblings(':eq(2)'));
}
$this.fadeOut(200, callback).fadeIn(400);
});

$("#prev-"+i).click(function(){
var $this = $(".video-album-"+i);
callback = function() {
$this.insertAfter($this.siblings(':eq(3)'));
}
$this.fadeOut(200, callback).fadeIn(400);
});
}





Is there anyone that could tell me a solution? I do not want to repeatedly create #next-3 #next-4 ids etc..

Thanks in advance.

Answer Source

Can you take a look at below approach:

$("[id^=next-]").click(function(){
    var current_id = $(this).attr("id");
    var number = current_id.replace("next-","");

    var $this = $(".video-album-"+number);
    callback = function() {
        $this.insertBefore($this.siblings(':eq(2)'));
    }
    $this.fadeOut(200, callback).fadeIn(400);
});

$("[id^=prev-]").click(function(){
    var current_id = $(this).attr("id");
    var number = current_id.replace("prev-","");

    var $this = $(".video-album-"+number);
    callback = function() {
        $this.insertAfter($this.siblings(':eq(3)'));
    }
    $this.fadeOut(200, callback).fadeIn(400);
});

Here we are using jQuery's starts with selector to attach the event to required DOM elements and within event handler we are grabbing the associated number for further process.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download