javascriptjquery

How to declare variables in jQuery the right way


I have this jQuery code that works in fiddle but not on my website!

I am working on this jQuery framework

https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js?ver=4.4.2

but it seems the variables are not declared properly according to console.log in Fox & I am getting the following error in Chrome.

Undefined variable: pagination Undefined variable: lis Undefined variable: next Undefined variable: toHighlight Undefined variable: prev

$(document).ready(function () {
    var $pagination = $('.qpagination');
    var $lis = $pagination.find('li:not(#qprev, #qnext)');
    $lis.filter(':gt(4)').hide();
    $lis.filter(':lt(5)').addClass('active');

    var $next = $('#qnext').click(function () {
        var idx = $lis.index($lis.filter('.active:last')) || 0;

        var $toHighlight = $lis.slice(idx + 1, idx + 6);
        if ($toHighlight.length == 0) {
            $prev.show();
            return;
        }

        $next.show();
        $lis.filter('.active').removeClass('active').hide();
        $toHighlight.show().addClass('active')
    });

    var $prev = $('#qprev').click(function () {
        var idx = $lis.index($lis.filter('.active:first')) || 0;

        var start = idx < 4 ? 0 : idx - 4;
        var $toHighlight = $lis.slice(start, start + 5);
        if ($toHighlight.length == 0) {
            $prev.hide();
            return;
        }

        $next.show();
        $lis.filter('.active').removeClass('active').hide();
        $toHighlight.show().addClass('active')
    });
});

This a demo of the code on Fiddle. it works fine on Fiddle though!

And here is the website I am working on (Click on Leave me a comment box)


Solution

  • Updated Your code a little bit https://jsfiddle.net/o3das45q/4/
    Added

    var $next = $('#qnext');
    var $prev = $('#qprev');