Jonathan Eggert
Jonathan Eggert

Reputation: 11

Comparing negative numbers in JQuery function

I am trying to compare two negative numbers and the comparison is failing. In this specific case, getLeftPercent() is a negative number (-14) yet when comparing, action B is performed. Logically, (-14) is less than (-10) thus action A should be performed.

If I change the right side comparison operand (-10) to a positive number (1 for example) then action A is performed. Is there some quirk of JavaScript that I'm overlooking (which is staring me in the face)? I can post the complete code but there's not really much more.

$(function() {

    // the statement in question
    if (parseInt(getLeftPercent(), 10) < -10) {
        // do action A
        // this is just a debug statement
        $('#posbanner').html('element position is less than negative 10');
    } else {
        // do action B
        // this is just a debug statement
        $('#posbanner').html('element position is greater than  or equal to negative 10');
    }
});

//  element left position on page
function getLeftPercent() {
    var leftStr = $('#sidebar').css('left'),
        pxPos = leftStr.indexOf('px'),
        leftVal = leftStr.substr(0, pxPos),
        leftPercent = (leftVal / $(window).width() * 100).toString(),
        dotPos = leftPercent.indexOf('.'),
        leftPercentStr = dotPos == -1 ? leftPercent  : leftPercent.substr(0, dotPos);
    return leftPercentStr;
};

Upvotes: 1

Views: 2246

Answers (3)

suff trek
suff trek

Reputation: 39777

Most likely your substrings return some characters before the number.

alert(parseInt('-14abc', 10)); // -14

alert(parseInt('abc-14', 10)); // NaN

Upvotes: -1

rink.attendant.6
rink.attendant.6

Reputation: 46218

Your getLeftPercent() function seems way overcomplicated. I'm not sure whether your "left" is relative to the document or parent element, I'll assume document here.

function getLeftPercent() {
    'use strict';
    return ( ($('#sidebar').offset()).left * 100 / $(window).width() );
}

Upvotes: 0

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

I tried running the following code on jsfiddle

if (parseInt( -14, 10) < -10)
{
alert("I am in A");
}
else
{
alert("I am in B");
}

I get I am in A Not sure, if getLeftPercent() is returning the value you expect.

Upvotes: 2

Related Questions