Search code examples
jqueryparseint

parseInt() not working as expected


I am custom coding an image slider right now and I am adding a data-slideNum attribute to each slider image and thumbnail image like so:

$('.slide').each(function(i) {
    $(this).attr('data-slideNum',i);
});

$('.thumbnail').each(function(i) {
    $(this).attr('data-slideNum',i);
});

Of course this numbers the slides 0-X. Below the slider I would like to put a caption that shows what number slide you are on so I am trying to add 1 to the slide number variable and slide total so the numbers are correct:

$('.slideNum').html(parseInt(x+1)+' of '+parseInt(slideTotal+1));

The 2nd parseInt() is working correctly, but the first one is concatenating instead of parsing.

So instead of 2 of 5 I am getting 21 of 5 and so on.

Any ideas?


Solution

  • You are performing string concatenation on x and 1, and then taking the int value.

    Essentially what you are doing is equivelent to:

    var x = "2";
    x = x + 1;
    parseInt(x);
    

    You can fix this by adding 1 to x after the parseInt call has returned an integer.

    $('.slideNum').html( 
         ( parseInt(x, 10) + 1 ) 
         + ' of '
         + ( parseInt(slideTotal, 10) + 1 )
       ); // closes .html
    

    In addition it is always a good idea to supply a radix to parseInt

    Also you don't need to add 1 to slideTotal if slideTotal is the length of the array, you also don't need to convert it to a int. So:

    $('.slideNum').html( ( parseInt(x, 10) + 1 ) + ' of ' + slideTotal);

    should suffice.