1

I am maintaining a project and I am seeing lots of parts that set size values this way:

var position = 500; // This value was calculated in some different way.
$someElement.css({
    left: position.toString() + "px"
});

I see that if I change it to

$someElement.css({
    left: position
});

it just works fine, but I can't find any documentation regarding older browsers, or some corner cases in which this won't work.

For me, it seems that adding the "px" adds a lot of noise to the code, but I am not sure if it is safe to remove.

I would like to know if there is any case in which this change won't work.

2
  • in most CSS properties, you need a unit (px, em, vh, in, mm, cm %, etc etc etc) - I don't think browsers assume px, but I could be wrong - when I say most, I mean ... all length/position properties that I can think of require a unit of measurement Commented Oct 2, 2018 at 2:25
  • BTW the call to toString is totally redundant, just position + "px" will do. Or are you trying to make it look bad on purpose? Commented Oct 2, 2018 at 2:38

1 Answer 1

0

It depends on what version of jQuery you're using. Older versions need a unit, but now they return the number itself. Usually in newer libraries when working in code you won't need to include px, and if it's working and not returning something like "(initial value)px+500" you're probably using a newer version. Just make sure the code isn't using vh, vw, rem, % or another sort of unit!

Check this other question out that might 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.