Using FancyBox to display an element’s dynamic content

December 3, 2011

I’ve been trying to find a nice modal/lightbox for jquery and I was recommended FancyBox. But what I needed it for was not wholly described in their examples. I needed to get some json from an ajax call, parse the data into some HTML and set that HTML to a div that would pop up in FancyBox.

function getData(id)
{
	$.post('/test', "id="+id, function(data){ $('#popup').html(generatePopup(data));});
}

That will get my json and the generatePopup function would create some content and set it to the #popup div.

I made sure to put the #popup div inside another hidden div. This ensures the popup html will not be displayed on the page. Now to add FancyBox, which ended up less straight-forward as I would have imagined it to be. It seems like FancyBox can only be tied to an anchor tag. So we have to add another layer on top of this.

The HTML:


And the Javascript:

$(document).ready(function() {
	$("a#inline").fancybox({
		'hideOnContentClick': true
	});
});
function getData(id)
{
	$.post('/test', "id="+id, function(data){ $('#popup').html(generatePopup(data)); $('a#inline').click();});
}

So the anchor tag will display #popup in FancyBox when clicked. We use jquery to automate that click in the ajax success function.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive