7

That's my question, and here's my example code.

HTML:

<a class="fancybox" rel="group" href="img1.jpg"> <img src="img1_thumb.jpg"> </a>
<a class="fancybox" rel="group" href="img2.jpg"> <img src="img2_thumb.jpg"> </a>

JS:

 var header = '<img id="w" src="logo.gif">';

$('.fancybox').fancybox({
    afterLoad: function() {
        this.wrap.prepend(header);
    }, // afterLoad
}); //fancybox

$('#w').click(function() {console.log('clicked');});

If you click a thumbnail to launch FancyBox, afterLoad will drop in the header, but when you click the image and watch the console you get nothing.

Thoughts? I'm trying to use FancyBox's $.fancybox.close() method, but if I can't get the click event to fire, I'm forced to using it inline, which I'd rather not do for the sake of not using JS inline.

Brian Whitton
  • 364
  • 1
  • 10

1 Answers1

2

You should either use .on() or equivalent to dynamically bind, or bind in the afterLoad callback. It has nothing to do with Fancybox: you're binding using a jQuery selector that matches something that doesn't yet exist in the DOM. Alternately you could try to bind directly to the element in memory, but you should grow comfortable with working with DOM binding first.

Matt Whipple
  • 7,034
  • 1
  • 23
  • 34
  • So would I put something like `$('#w').on('click',function(){$.fancybox.close()})` in the `afterLoad` function after prepending the header? – Brian Whitton Sep 13 '12 at 23:22
  • Just thought I'd add that binding the `$.fancybox.close()` function in the `afterLoad` callback wasn't optimal. When you scroll to the next image the 'new' header doesn't handle the event. I fixed it by moving the click handler to an `afterShow` callback. – Brian Whitton Sep 14 '12 at 15:39