3

I can't make this little thing work. Don't know what's the problem, but my array elements can't get defined, alert always gives me back NaN. Tried to alert the jQuery selectors, they're working perfectly. What's the problem?

        var sldr                                = $("#slider img"),
            count                           = sldr.length-1,
            containerHeight         = $("#slider").css('height'),
            images                          = new Array(),
            imgHeights                  = new Array(),
            imgWidths                       = new Array(),
            imgSlices                       = new Array(),
            choosenSlice                =   '',
            slicer                          = '';


        var i=0;
        for (i=0;i<=count;i++){
            images[i]               = $("#slider img:eq("+i+")");
            imgHeights[i]       = $("#slider img:eq("+i+")").attr('height');
            imgWidths[i]        = $("#slider img:eq("+i+")").attr('width');
            imgSlices[i]        = (Math.round(imgHeights[i]/containerHeight))-1;
            alert(imgSlices[i]);
        }

1 Answer 1

3

If the 'height' or 'width' attribute isn't set on one of the images, or isn't a number, then trying to divide with it might result in a NaN result.

Try converting those values to a number using parseInt:

mgHeights[i]       = parseInt($("#slider img:eq("+i+")").attr('height'));
imgWidths[i]       = parseInt($("#slider img:eq("+i+")").attr('width'));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it worked. But why i can't store other than numbers? codeimages[i]=$("#slider img:eq("+i+")");code this will be an object for example... And they are set in the <img> tag... can't understand...
You can store things other than numbers, but doing math with them will result in NaN. Attributes on the tag like height and width ultimately are strings -- they might just be string representations of numbers, but they are still a string type. It sounds like what might be happening is that even if you set a width of "400", the browser might interpret it as "400px". The extra non-number characters are probably preventing it from being treated as a number without parsing.
Just to clarify, the real issue here is division of strings (on the next line), and that is solved by storing numbers instead of strings for the values used in the division. In general, you can store whatever you want in an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.