Assistance tweaking a script

Hey guys,

I have this script:

    $(".slider-side-prev").each(function () {
        $(this).on('click', function (event) {
            event.preventDefault();
            if ($(this).parents('.slider-right').find(".active-slide").index() > 0) {
                $(this).parents('.slider-right').find(".active-slide").fadeOut(function () {
                    $(this).removeClass("active-slide");
                    $(this).prev("li").addClass("active-slide").show();
                });
            }
        });
    });

I have both a left and right click nav scripts. I want some assistance rewriting the script so that when the number of items in the list is finished, the next or previous arrows should be greyed out.

Any point in the right direction will be highly appreciated - so far the script is able to count, I am not sure how I can easily change it.

Can you provide a demo of this not working (JSFiddle or something)?

You’d just check if the index of the currently active slide equals 0 or the number of slides - 1 respectively. BTW, there’s quite a bit redundancy in your code; the each in the first line is not necessary, and you’re creating 5 jQuery objects (also with redundant DOM queries) where you only need one from this and one from the active slide. It would be much more efficient to just store those references in a variable; with the additional check it might look like e.g.

$(".slider-side-prev").on('click', function (event) {
    var $this = $(this),
        active = $this
            .parents('.slider-right')
            .find(".active-slide");
        
    event.preventDefault();
    if (active.index() === 0) return;
    
    active.fadeOut(function () {
        active = active
            .removeClass("active-slide")
            .prev("li")
            .addClass("active-slide")
            .show();

        if (active.index() === 0) {
            $this.addClass('greyed-out');
        } else {
            $this.removeClass('greyed-out');
        }
    });
});
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.