I need to load content with dynamic width within Fancybox iframe. To achieve resizing of the iframe to fit the content, I need to pass the content width to Fancybox call. I have done this using the following:
jQuery('#container').on('click', '.fancybox-iframe', function(e){
e.preventDefault();
var iframeWidth = parseInt(jQuery(this).attr('id'));
jQuery(this).fancybox({
width : iframeWidth,
height : '100%',
autoSize : true,
fixed : true,
type : 'iframe',
loop : false,
padding : 0,
closeBtn : false,
afterLoad : function() {
jQuery('body').css('overflow', 'hidden');
},
afterClose : function() {
jQuery('body').css('overflow', 'auto');
},
helpers : {title: {type: 'outside'}, overlay: {opacity: 0.8, css: {'background-color': '#FFFFFF'}}, thumbs: {width: 50, height: 50}, buttons: {}}
});
});
The HTML for the above:
<a id="<?php echo $content_width; ?>" class="fancybox-iframe fancybox.iframe" rel="gallery" href="<?php the_permalink(); ?>"></a>
<a id="<?php echo $content_width; ?>" class="fancybox-iframe fancybox.iframe" rel="gallery" href="<?php the_permalink(); ?>"></a>
<a id="<?php echo $content_width; ?>" class="fancybox-iframe fancybox.iframe" rel="gallery" href="<?php the_permalink(); ?>"></a>
The above code has two issues: First, I have to click the hyperlink twice, every time for Fancybox to appear. The second issue is that, this does not work with the rel attribute of the HREF and therefore does not display content as a Fancybox gallery. To overcome the gallery issue, I replaced jQuery(this).fancybox({ with jQuery('.fancybox-iframe').fancybox({. This made the galleries feature work. However, Fancybox now only takes the value of iframeWidth variable for the first link clicked.
Any ideas on how to pass content width variable to Fancybox and also maintain the gallery feature? BTW, I am working with Fancybox 2.0.5
If you are using fancybox v2.x, you don’t need to use jQuery
.on()method since fancybox already uses “live” soshould do the trick.
UPDATE:
I have revised my code above and actually things can be much simpler than expected.
The following code allows you to pass the
widthparameter dynamically through theIDAND have a gallery of iframes (with just a single click). Just add to theafterLoadcallback this :Notice that you don’t need to set the option
width.OPTION 2
Alternatively you could also pass the
widthparameter dynamically using thedata-widthattribute (if you are using HTML5DOCTYPE) instead of theID(and use theIDfor what it matters). I think that would be a more elegant solution.Your html then should look like
and the javascript is pretty much the same
I have set a DEMO with the two options that you can see here
Last note: Fancybox uses a
paddingof 15px so the totalwidthwill beiframeWidth + 30, unless you set thepaddingoption to0.