0

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);
        }
    });
});
Relm
  • 7,923
  • 18
  • 66
  • 113

1 Answers1

2

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);
    }
venkat7668
  • 2,657
  • 1
  • 22
  • 26
  • Its exactly like that in the example on the question. – Relm Aug 05 '15 at 06:52
  • To be honest I don't know why you've been downvoted, the error is mine, I forgot to parseInt on the second condition block. Had only passed it on the first. – Relm Aug 05 '15 at 07:00