[Solved] Optimize Javascript code [closed]


You could use a JQuery function called toggleScript, that will make your code shorter. Also it would be better to call all your variables not only num1 and num2 in order to make your code more readable. When you saved an element into a variable – you don’t have to call ${} one more time, use the variable instead.

$("document").ready(function() {
    var menu = $('#menu'); //nav
    var html2 = $('#HTML2'); //nav2

    var menuOffsetTop = menu.offset().top; //num
    var html2OffsetTop = html2.offset().top; //num2


    $(window).scroll(function() {
        var w = $(this);

        menu.toggleClass('menu-scroll' , (w.scrollTop() > menuOffsetTop) );
        /* 
        The same as
        if (w.scrollTop() > menuOffsetTop) {
            menu.addClass('menu-scroll') ;  
        } else {
            menu.removeClass('menu-scroll');
        }
        */
        html2.toggleClass('html2fixs' , (w.scrollTop() > html2OffsetTop) );
    });

    $('#BackToTop').click(function(){
        $('html, body').animate({scrollTop : 0},300);
    });
});

1

solved Optimize Javascript code [closed]