Search code examples
jqueryhtmlfancybox

Fancybox not working on dynamically added external links


I have a list of items as follows

<ul>
 <li><a href="http://toExtUrl/img.jpg" class="should-popout">
  <img src="http://mywebsite.com/icon.png"></a>
 </li>
</ul>

toExtUrl/img.jpg is added dynamically and it may sometimes shows pdf or HTML content instead of images(This is always external link). I'm trying to give the fancybox popout effect for whatever comes with href attribute of '.should-popout'.

But while clicking it just redirection to external url happens. My fancybox option is as follows

$(window).load(function(){
 $('a.should-popout').fancybox({
    'autoDimensions' : true,
    'autoScale' : true
    'hideOnContentClick': true,
    'showCloseButton' : true
 });
});

What may be the error in the setup.


Solution

  • I would suggest you to upgrade to v3 and use like this:

    $().fancybox({
      selector : '.should-popout'
    });
    

    v2 tries to get current selector (using this handy https://api.jquery.com/selector/ property) and then uses that to create delegated event handler. But jQuery v3 removed that feature and therefore this does not work anymore. And therefore v3 allows this new syntax.