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;
}
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");
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.
var width = $(window). width();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With