M-S M-S - 6 months ago 26
HTML Question

How to animate the custom vertical slider Jquery

Currently on click of next and prev, the height of the list is adjusting. Instead of increasing and decreasing the height, i want to replace the current content with new set of content.

Expectation:


  1. if I click on next/ prev, current visible list should replace with the new set of items with some slide animation.

  2. Also every time I need to display 3 items, in current scenario once the next/prev iteration is completed, only 2 items are getting visible.



This is what I tried:

JS:

$(document).ready(function () {
size_li = $("#list li").size();
x=3;
$('#list li:lt('+x+')').show();
$('#next').click(function () {
x= (x+3 <= size_li) ? x+3 : size_li;
$('#list li:lt('+x+')').show();
$('#prev').show();
if(x == size_li){
$('#next').hide();
}
});
$('#prev').click(function () {
x=(x-3<0) ? 3 : x-3;
$('#list li').not(':lt('+x+')').hide();
$('#next').show();
if(x < 3){
$('#prev').hide();
}
});
});


JS Fiddle:

Demo Link

Answer

I approached the problem a bit differently. Here's the fiddle.

The gist of my solution is that I've used jQuery's animate function to do the smooth scrolling effect:

$('ul').animate({
    scrollTop: $('ul').scrollTop() + height_to_show
}, 500);

One catch, however, is that the ul and the li elements need to have fixed heights. These heights are calculated internally based on the following variables set by you:

/**
 * Total number of elements in the list
 * @type {Number}
 */
var num_of_elems = 8;

/**
 * Static height of each element (in pixels)
 * @type {Number}
 */
var height_of_elem = 25;

/**
 * Number of elements you want to show in the page
 * @type {Number}
 */
var num_of_elems_to_show = 3;

/**
 * The visible height of the ul
 * @type {Number}
 */
var height_to_show = 0; //calculated internally

UPDATE

Here's the updated fiddle.

I've added functionality to hide or show the prev and next button based on the current page being displayed.

/**
 * Show or hide the prev and next button depending on the current_page
 */
var show_hide_buttons = function() {
    if (current_page === Math.ceil(num_of_elems / num_of_elems_to_show) - 1) {
        $('#next').hide();
    } else {
        $('#next').show();
    }

    if (current_page === 0) {
        $('#prev').hide();
    } else {
        $('#prev').show();
    }
};