Detecting width: auto in jQuery - javascript

I'm retrieving the width of elements using jQuery and would prefer it if I could have an indication of whether there was an explicit width (and height) specified.
<div id="test"></div>
<script type="text/javascript">
$(function() { alert($('#test').css('width')); });
</script>
This will alert the implicit width of the div in terms of how many pixels it takes up on the client's screen. Is there any way that if the width is either missing or set as width: auto that it can be verified using jQuery?
That is, instead of the above example returning an integer, it would return either auto or undefined. Or, alternatively, is there an equivalent of a isAuto function?

This will get either string "auto" or "180px" on absolute values.
$('element').prop('style').width
for width or
$('element').prop('style').height
for height.

I don't believe it's possible for the moment. At least not in any other browser than IE. IE implements element.currentStyle which represents styles at they were written in the CSS file. On the other hand, the rest of the browsers implement window.getComputedStyle which returns the computed values of those styles. That's what you receive there, a numeric value instead of auto.
The only way around it would be to parse CSS declarations from document.styleSheets.
References:
http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx
https://developer.mozilla.org/en/DOM:window.getComputedStyle
https://developer.mozilla.org/en/CSS/computed_value

$('#test')[0].style.width=="auto" should work: http://jsfiddle.net/KxTLE/ and http://jsfiddle.net/KxTLE/1/
Try
jQuery.fn.isAuto=function() {
if(this[0]) {
var ele=$(this[0]);
if(this[0].style.width=='auto' || ele.outerWidth()==ele.parent().width()) {
return true;
} else {
return false;
}
}
return undefined;
};
And example: http://jsfiddle.net/KxTLE/6/

As far as I know, there is no native jQuery function to detect auto widths or heights. So I wrote a plugin to do it.
$.fn.isAuto = function(dimension){
if (dimension == 'width'){
var originalWidth = this.innerWidth();
var marginLeft = parseInt(this.css('margin-left'));
var testMarginWidth = marginLeft+50;
this.css('margin-left', testMarginWidth);
var newWidth = this.innerWidth();
this.css('margin-left', marginLeft);
if(newWidth<originalWidth){
return true;
}
else{
return false;
}
}
else if(dimension == 'height'){
var originalHeight = this.height();
this.append('<div id="test"></div>');
var testHeight = originalHeight+500;
$('#test').css({height: testHeight});
var newHeight = this.height();
$('#test').remove();
if(newHeight>originalHeight){
return true;
}
else{
return false;
}
}
};
Originally, I had written it to do height, so I just expanded it to include width. You just call it like this:
$('#element').isAuto('width');
or
$('#element').isAuto('height');
Here is a fiddle demonstrating the plugin's functionality.

I am not quite sure if I am answering your question correctly, but if you use the width() function this will give you an integer representing the rendered width in pixels.

create function
pass css element id to function
write a case where statement to be performed on the width property of the element id
NOTE: to use on mulitple elements would be wise to use a loop with an array of element names

Related

jQuery image resizing issue

I've found this line of code somewhere using firebug and I know you need to put something where I've put the 3... behind parseFloat, but I have no idea what.
It works when I fill in a random number but the width is never the correct one and want to use it on several pages with photographs so it's always the correct size.
script type="text/javascript">
var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
$(document).ready(function(){
var scaledwidth = ((parseFloat(...)*($(window).height()/4000))+50).toFixed(0);
if (badBrowser) {
$('#container img').css('height',$(window).height()+'px');
}
$('#container').css('width',scaledwidth+'px');
imageresize();
});
jQuery(window).resize(function() {
var scaledwidth = ((parseFloat(...)*($(window).height()/4000))+50).toFixed(0);
if (badBrowser) {
$('#container img').css('height',$(window).height()+'px');
}
$('#container').css('width',scaledwidth+'px');
imageresize();
});
function imageresize() {
var height = $(window).height();
if ((height) > 1340){
var quality='1440';
} else if((height) > 980) {
var quality='1080';
} else if((height) > 680) {
var quality='720';
} else if((height) > 480) {
var quality='640';
} else {
var quality='320';
}
}
</script>
Thanks in advance!
It looks to me like the value you need to put there depends on the sum of the widths of all the images; so you can't just pick a value that works for all pages.
On the other hand, it also seems like a bad solution to the problem of keeping the images next to each other. Why set the width of the container? If you just ensure white-space doesn't wrap then all the images should sit next to each other without worrying about the container's width.
#container
{
white-space: nowrap; /* keep images on the same line */
font-size: 0; /* removes whitespace between images */
}
http://jsfiddle.net/f8y4Z/
From the javascript, we now only need the imageresize() (provided we use it to set different quality source images), and trigger it on ready and resize; no magic numbers required.
(For backwards compatibility with browsers that don't or poorly support white-space, you could use <nobr></nobr>)

Can't set elements height to its scrollHeight?

I can't for some reason make a smooth div, I'm trying to make it expand and contract when I click a button, but it doesn't work.
Javascript:
function expandContract(id) {
var object = document.getElementById(id);
if (object.style.height != "0px") {
object.style.height = "0px";
} else {
object.style.height = object.scrollHeight;
}
}
HTML:
<div id='test' style='overflow:hidden;'>
Test pest fest.
</div>
<button onClick='expandContract("test");'>Expand/Contract</button>
jsFiddle
I've also tried setting it do max-height, but still I can't get it to expand again. How would I do this without any javascript plugins?
You're missing +"px". You are required to set a unit (em, px, %, etc) when using style.height. Because scrollHeight gives you just a numeric value, you must append the units which are px in this case.
function expandContract(id) {
var object = document.getElementById(id);
if (object.style.height != "0px") {
object.style.height = "0px";
} else {
object.style.height = object.scrollHeight+"px";
}
}
jsFiddle
I got it to work in Chrome, as is.
IE when I changed the 'overflow' to 'scroll'.

Javascript - how to call function correctly

I don't really understand how to call a Javascript function properly on document ready. My goal is to resize a div depending on the height of browser window, and I took this code from another answer on SO. What am I doing wrong?
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
$(document).ready(resizeElementHeight($('#global_image')));
The element I am trying to call has the id "global_image", but I get "cannot set property height of undefined", and I feel lost in how to providing the right element to the function. Thanks for your help!
ready() expects a function as its argument. Right now, you are calling resizeElementHeight() and passing its return value to ready().
In your current code, at the point of calling resizeElementHeight() the DOM is not yet ready and the element #global_image is not yet in the DOM tree.
You should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image'));
});
The function resizeElementHeight expects a DOM-element, not a JavaScript object. To expand on techfoobar's answer you should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});
the DOM object is not completely loaded when you call resizeElementHeight.replace by is:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});

jquery Element to DOM Element returns empty string by function

Why does this code:
function fn(el){ return $(el)[0].style.width };
fn('#someElementIdId'); // return -> ""
But this code...
function fn(el){ return $(el).width() } ;
fn('#someElement'); // return -> correct width
I have tried different things, but all have the same result...
How can I make the first code work?
CODE HERE :: http://jsfiddle.net/A2VpH/18/
Yes, is there, and don't works... Any DOM's property properly set up
... don't works. Make a REAL test for yourself
Here's a test showing jQuery vs regular DOM: http://jsfiddle.net/A2VpH/3/
Works fine for me.
The "style" attribute does not contain all the style information for an element. It's just the stuff that's there directly in the tag, like:
<div style='width: 100px'>
If the width comes from CSS, it won't be there.
You can use offsetWidth, clientWidth, or a currentStyle/getComputedStyle hybrid depending on your browser:
HTML
<div id="someElementIdId"></div>
CSS
div {
width: 200px;
padding: 20px;
margin: 20px;
border: 5px solid black;
}
Javascript
function getStyle(x,styleProp)
{
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
function fn1(el){ return $(el)[0].currentStyle.width; };
function fn2(el){ return $(el).width(); };
function fn3(el){ return getStyle($(el)[0],'width').replace('px', ''); };
function fn4(el){ return $(el)[0].offsetWidth; };
function fn5(el){ return $(el)[0].clientWidth; };
alert( fn3('#someElementIdId') );
Note that offsetWidth will include the padding, scrollBar, and the border. If you want width + padding you can use clientWidth.
It also might help to know why you want to do this? If you are going to be using jQuery to find the element in the DOM why not use the jQuery width() function as well?
http://jsfiddle.net/A2VpH/24/

How to find actual rendered values of elements set to 'auto' using JavaScript

Suppose I have the following html, and no CSS
<div>
here is some content in this div. it stretches it out
<br />and down too!
</div>
Now I want to get the actual pixel width and height that the browser has rendered this div as.
Can that be done with JS?
Thank you.
Try getting a reference to your div and reading the offsetWidth and offsetHeight properties:
var myDiv = document.getElementById('myDiv');
var width = myDiv.offsetWidth; // int
var height = myDiv.offsetHeight;
offsetWidth/Height cumulatively measures the element's borders, horizontal padding, vertical scrollbar (if present, if rendered) and CSS width. It's the pixel values of the entire space that the element uses in the document. I think it's what you want.
If that is not what you meant, and you'd rather only the element's width and height (i.e. excluding padding, margin, etc) try getComputedStyle:
var comStyle = window.getComputedStyle(myDiv, null);
var width = parseInt(comStyle.getPropertyValue("width"), 10);
var height = parseInt(comStyle.getPropertyValue("height"), 10);
The values above will be the final, computed pixel values for the width and height css style properties (including values set by a <style> element or an external stylesheet).
Like all helpful things, this won't work in IE.
You say you are using jQuery. Well it's trivial now, and works cross-browser:
var width = $('div').css('width');
var height = $('div').css('height');
With jQuery you don't need the first part of this answer, it's all taken care of for ya ;)
One of the benefits of using a framework, like Prototype, is that the framework authors have usually sorted out the portability issues. Even if you don't use the framework, it can still be instructive to read. In the case of Prototype, the code for reading the dimensions of an element accounts for a Safari issue and allows you to read the width of an element that is not presently dislayed.
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
For the jQuery framework, .height and .width do the job.

Categories

Resources