Convert CSS Width String to Regular Number

Convert css width string to regular number

If it always returns in px format, "100px", "50px" etc (i.e. not "em" or percent), you could just...

var width = parseInt($("#myelem").css("width"),10); // always use a radix

or

var width = parseInt(element.style.width,10); // always use a radix

It ignores the "px" suffix so you should be good to go.

Although deep down I'm thinking that something isn't right if $("#myelem").width() isn't working.

Note on hidden elements.

If you are adding jQuery to progressively enhance you page, the element you are calculating should be visible when the page first loads. So you should get the width before you initially hide the element. By doing this, $("#myelem").width() will work.

var myWidth = 0;

$(document).ready( function () {
myWidth = $("#myelem").width();
$("#myelem").hide();
});

Is there a way to get a number value from a style type using JavaScript?

parseInt ignores everything after and including the first non-digit character:

> parseInt("100px", 10)
100

Can CSS convert a string to integer?

No. And you cannot use an attr(...) construct as the value of a normal property, only in the value of a content property.

Instead of data-width attributes, you could use just style attributes. Not ideal, but more logical than to use data-* attributes to carry style info.

How to get just numeric part of CSS property with jQuery?

This will clean up all non-digits, non-dots, and not-minus-sign from the string:

$(this).css('marginBottom').replace(/[^-\d\.]/g, '');

UPDATED for negative values

Scss how convert string to numeric value

It would probably be better to use a helper function to remove the unit of $font-size such as this one.

@function stripUnit($number) {
@if meta.type-of($number) == "number" and not math.is-unitless($number) {
@return math.div($number, $number * 0 + 1);
}

@return $number;
}

@function em($value, $font-size) {
$data: strip-unit($font-size);
$result: math.div($value, $data);

@return $result + "em";
}

Divide given value by .style.width in Javascript

width will be string. Convert it to number before dividing. This example uses getComputedStyle to get actual width of a dom element

let elem = document.getElementById('test');let compStyles = window.getComputedStyle(elem);const widthInteger = parseInt(compStyles.width, 10);const halfWidth = widthInteger / 2;console.log(halfWidth)
.test {  height: 200px;  width: 200px;  border: 1px solid green;}
<div class='test' id='test'></div>

Number() method doesn't give me proper output

I think you can use parseInt(image.width) (or image.height).

Get a number for a style value WITHOUT the px; suffix

parseInt gives you the numerical value:

var tmp = parseInt(document.getElementById(nameVar).style.left, 10);
console.log(tmp);

or, as @PeteWilson suggests in the comments, use parseFloat



Related Topics



Leave a reply



Submit