user3638239 user3638239 - 6 months ago 14
Javascript Question

jquery .each - strange calculation

I'm using .each to cycle through elements on the page and see the maximum bottom value. Script seems to be ok except that a simple check between two values returns something weird and I can't directly figure out what I have done wrong.

Here is my div setup:

<div id="zone1" data-top="38" data-bottom="1648" data-left="131" data-width="467" data-group="0">...</div>
<div id="zone2" data-top="38" data-bottom="957" data-left="597" data-width="467" data-group="0">...</div>
<div id="zone3" data-top="38" data-bottom="4508" data-left="1064" data-width="467" data-group="0">...</div>


Now the script:

maxb = 0;
console.log('init max '+maxb);
$('[data-group=0]').each(function()
{
tempb = $(this).attr('data-bottom');
console.log(tempb+' '+maxb);
if (tempb>maxb)
{
maxb = tempb;
}
console.log(tempb+' '+maxb);
});


The objective of this script is to store the maximum data-bottom value of the data-group 0.

If I now look at my console output:

init max 0
1648 0
1648 1648
957 1648
957 957
4508 957
4508 957


So maxb is correctly initialized. The first data bottom is bigger than 0 so maxb takes this value but the second iteration is weird as 957 is below 1648, maxb should still be 1648 but it takes 957 as a max value and keeps it until the end. It's like the IF condition was not working properly but I probably need some sleep, I don't see where the issue is.

Thanks
Laurent

Answer

Are you sure these numbers are being treated as integers? I know you can use parseInt() to get javascript to force a string to be treated as a number but I'm lazy so I always just multiply by 1, which essentially does the same thing.

So basically, you would just change the code to be:

tempb = $(this).attr('data-bottom')*1;