Search code examples
javascriptjqueryincrementparseint

How to increment a variable by another variable in javascript


Full Code below

I want to add a number from a variable to the incrimented variable, but they don't add. instead they get concatinated.

This line

countScroll-=parseInt(scrollWidth_g);

if "scrollWidth_g" is 300 and "countScroll" is 10, i get 10300 and i want 310;

$(document).ready(function(e) {
    var countScroll = 10;
    $(document).on('click', '.scroller_g_nav', function(){
        var nav = $(this).attr('data-nav');
        var scrollWidth = $('.scroller_g').attr('data-scrollwidth');
        if (typeof scrollWidth == 'undefined'){
        var scrollWidth_g = 200;
        } else {
            var scrollWidth_g = scrollWidth;
            }

        if (nav == 'left'){         
                countScroll-=parseInt(scrollWidth_g);
                $('.scroller_g').animate({scrollLeft:countScroll},600);
            } else {
                countScroll+=scrollWidth_g;
                $('.scroller_g').animate({scrollLeft:countScroll},600);
        }
    });
});

Solution

  • You dont need to parse string number ("123") when you substract, but it is needed when you add the numbers.

    Example: "12" - 1 = 11
             "12" + 1 = 121 //here you need to parse string to number to get correct result 
             parseInt("12") + 1 = 11 
    
    
    It works : 
    
        if (nav == 'left'){         
                    countScroll -= parseInt(scrollWidth_g);
                    $('.scroller_g').animate({scrollLeft:countScroll},600);
                } else {
                    countScroll += parseInt(scrollWidth_g);
                    $('.scroller_g').animate({scrollLeft:countScroll},600);
        }