2

The following 2 code snippets produce very different outcomes:

This one works as supposed: It increases the progressbar value (width) by 5 each second.

function doIncrement(increment) {
    w = parseInt(document.getElementById('internal-progressbar').style.width);
    document.getElementById('internal-progressbar').style.width = (w + increment) + '%';
    if (parseInt(document.getElementById('internal-progressbar').style.width) < 100)
    {
        setTimeout(function () { doIncrement(increment) }, 1000);
    }
}

This one (getelementbyid replaced with jquery selectors) produces an entire different outcome. It starts by increasing by 5 but then it increases by 34 and then by even more.

function doIncrement(increment) {
    w = parseInt($('#internal-progressbar').css('width'));
    $('#internal-progressbar').css('width', (w + increment) + '%');
    if (parseInt(document.getElementById('internal-progressbar').style.width) < 100)
    {
        setTimeout(function () { doIncrement(increment) }, 1000);
    }
}

What's causing this difference? I truly don't understand.

Here's a jsfiddle that demonstrates the issue: http://jsfiddle.net/k79Ph/

5
  • Have you tried adding console.log(w) to see what's being returned? Commented Nov 16, 2013 at 15:00
  • Do these exist in the same scope? Does the difference continue if you declare w properly as var w = parseInt...? Commented Nov 16, 2013 at 15:01
  • Why don't you use jQuery's .width() in the second place? Commented Nov 16, 2013 at 15:03
  • @still_learning you can still set the width with .width() you know. :) api.jquery.com/width/#width-functionindex--width Commented Nov 16, 2013 at 15:09
  • @TusharGupta I tried making a fiddle (never done it before) but I couldn't even get the js function to be called properly. Anyways here it is: jsfiddle.net/k79Ph Commented Nov 16, 2013 at 15:10

1 Answer 1

4

The problem is that css('width') returns the absolute size (in pixels), whereas style.width is the "raw" value (percentage). This thread should help you.

Sign up to request clarification or add additional context in comments.

Comments

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.