Jump to content

[SOLVED] get width and height without PX


glenelkins

Recommended Posts

Hi  i have this js code

 

		var element_width =  _e_object.style.width;
		var element_height = _e_object.style.height;

 

i need to play with the values by adding to them but its returning with PX on the end, how do I get the width and height just as a number?

 

Link to comment
https://forums.phpfreaks.com/topic/88171-solved-get-width-and-height-without-px/
Share on other sites

Well, this is mainly a CSS-cross browser problem.

 

FireFox does not require you to define PX (as it's set default) in CSS width/height. However, IE requires that you do this or it won't display the object that has the style settings correctly. The best way to handle this is to create a simple function that will add or subtract from the width and height, and then reformat the string and return it to you.

 

function add_pixels(scalar,object){//scalar = how much to add (positive or negative); object = what you're changing
var ob_array = object.split(" ");//cut it apart
//ob_array[0] = pixel value; ob_array[1] = "PX" or any other measurement
ob_array[0] = ob_array[0]*1;scalar = scalar*1;//quick hand of making sure that javascript reads as numbers and not strings
ob_array[0] = ob_array[0] + scalar;
var object = ob_array.join(" ");//glue it together
return object;
}

 

And then, to call it..

 

_e_object.style.width = add_pixels(5,_e_object.style.width);
_e_object.style.height = add_pixels(-10,_e_object.style.height);

 

Well, the best way you can do it is just remove the "px" and add it back in...

 

Or, if you're really smart, you just use RegEx.

 

//pattern would be
var pattern = ~([0-9])*(^[0-9])*~;

 

Where the number fits into the first section, and everything else that's not a number in the second var.

 

That should give you a kick in the right direction.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.