Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Javascript css("width") / check if style is defined in css?

I have a stylesheet which defines default width for images. When I read the image width style with jQuery width() it returns the right width. It also returns the same width when I call css("width"). But if there is no width defined in the stylesheet the function css("width") will also return the computed width() value but won't say undefined or auto or something like that.

Any ideas how I could find out if style is or is not defined in the CSS code?

Solution works for me cross browser. Thanks to everyone for helping:

$(this).addClass("default_width_check");
var width = ($(this).width() == 12345) ? 'none-defined' : $(this).width();
var height = ($(this).height() == 12345) ? 'none-defined' : $(this).height();
$(this).removeClass("default_width_check");

.default_width_check {
    width: 12345;
}
like image 474
i3rutus Avatar asked Nov 05 '10 11:11

i3rutus


People also ask

How can check CSS property value in jQuery?

Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");

What does CSS (' width ') and width () Change width of?

The width CSS property sets an element's width. By default, it sets the width of the content area, but if box-sizing is set to border-box , it sets the width of the border area.

How can check window width using jQuery?

var width = $(window). width();


1 Answers

I have a workaround idea that might work.

Define a class named default_width before all other style sheets:

.default_width { width: 1787px }  
/* An arbitrary value unlikely to be an image's width, but not too large
   in case the browser reserves memory for it */

to find out whether an image has a width set:

  • Clone it in jQuery: element = $("#img").clone()

  • give the cloned element the default_width class: element.addClass("default_width")

  • If its width is 1787px, it has no width set - or, of course, is natively 1787px wide, which is the only case in which this method will not work.

I'm not entirely sure whether this will work, but it might. Edit: As @bobince points out in the comments, you will need to insert the element into the DOM for all classes to be applied correctly, in order to make a correct width calculation.

like image 200
Pekka Avatar answered Nov 07 '22 10:11

Pekka