Sometimes there are special requirements for the width restrictions of a website. For example the width of the panel has to be at least 100px, but should not exceed 800px.
The first approach is to use the CSS attributes min-width/max-width
. But these will not work in MS Internet Explorer. There are several IE6-workarounds like using Javascript-based CSS-expression, but i think those are ugly.
The following approach uses easy Javascript scripting: Calculate the width using jQuery, compare it to the reference width and set it to the min-/max-value if needed.
Simple usage:
setMinMaxWidth(100,800, 'myDivID');
This code also can easily be adapted for min-/max-height
.
Note: You cannot get the width of an invisible element. So you have to make the element visible before invoking the methods.
Sources:
/**
* Utility method to help jQuery work with JSF clientIds.
* http://cagataycivici.wordpress.com/2009/05/14/jquery-and-jsf-ids/
*/
function escapeClientId(id) {
return "#" + id.replace(/:/g,"\\:");
}
/**
* Set the max-width of the element.
* @param maxWidth max-width in pixels
* @param element element
*/
function setMaxWidth(maxWidth, element){
var item=jQuery(escapeClientId(element));
if (null==item){
return;
}
var width=item.width();
if (null==width || 0==width){
//element not found or not visible
return;
}
//if content-width>max-width then resize to the max-width
if (width>maxWidth){
item.width(maxWidth);
}
}
/**
* Set the min-width of the element.
* @param minWidth min-width in pixels
* @param element element
*/
function setMinWidth(minWidth, element){
var item=jQuery(escapeClientId(element));
if (null==item){
return;
}
var width=item.width();
if (null==width || 0==width){
//element not found or not visible
return;
}
//if content-width<min-width then resize to the min-width
if (width<minWidth){
item.width(minWidth);
}
}
/**
* Set the width within the range of min..max of the element.
* @param minWidth min-width in pixels
* @param maxWidth max-width in pixels
* @param id id of the element to resize
*/
function setMinMaxWidth(minWidth, maxWidth, id){
setMinWidth(minWidth, ''+id);
setMaxWidth(maxWidth, ''+id);
}