Category: jQuery

Autofit an image in a div using JQuery

I had a problem with one of my current projects where I was supposed to have an image enclosed in a div with fixed dimensions.

<div id="resize-div">
<img src="someimage.jpg", :id="resize-div">
</div>

For the dimensions of the div, you can set it inline or use css file:

#resize-div {
width:466px;
height:133px;
}

Now since not all images will fit this aspect ratio you’ll encounter problems easily enough. With images smaller than the div, I had little problem letting the css to handle it so it’s situated perfectly center in the div. I didn’t include it here to shorten the codes i need to display :).

Judging from the code shown above, you’ll not that if you have larger images that exceeded the div’s set height and width (especially those width different aspect ratios), a pure css solution simply won’t work (or at least I couldn’t make it work…. :/) so I thought of using JQuery to work it out for me.

Here’s my script to autofit images in a div using JQuery.

$(function(){
	var divElem = $("#resize-div");
	var maxht = divElem.height();
	var maxwdt = divElem.width();
	var imgElem = $("#resize-image");
	var ht = imgElem.height();
	var wdt = imgElem.width();
	if (ht < wdt){
		if (wdt > maxwdt)
			$("#resize-image").css({'height' : "auto", 'width' : maxwdt});
		else
			$("#resize-image").css({'height' : "auto", 'width' : wdt});
	}
	else if (ht > wdt){
		if (ht > maxht)
			$("#resize-image").css({'height' : maxht, 'width' : "auto"});
		else
			$("#resize-image").css({'height' : ht, 'width' : "auto"});
	}
});

Using jQuery datepicker with Facebox

Facebox is an interesting jquery plugin but it’s also one of those annoying things on the web that likes to break stuff around it.  For my current project, I needed to use jQuery’s datepicker plugin with facebox. As expected, facebox broke datepicker :(.  I wanted to try several other implementations but since jQuery’s datepicker was the simplest one I could find, I didn’t want to waste time trying make another script work.  So I took a few minutes to debug my problem.

The problem:

Turns out that datequery relies on an elements ID.  The problem?  Facebox duplicates all the contents of the div you wanted to display and all hell breaks loose.

The solution:

Quite simple actually.

Just use jQuery to replace the element id within facebox at run time.

Here’s the script:

$(document).bind('reveal.facebox', function() {
  $('#facebox .datepicker').each( function(intIndex){
    $(this).attr('id',jQuery(this).attr('id') + '-2')
  });
});

Then just modify your binding for datepicker accordingly:

$(document).bind('reveal.facebox', function() {
	$('#date_filed_for-2').datepicker();
})

And you’re done. 😀

I found this code using google-fu on frenzicmojo.net