Your code does not work because this $.fancybox();
fancybox doesn't tell what to open does nothing.
What would I do if you do not want to edit each link in your html, this:
1). add the ID
tag to the <ul>
tag so that we can use this type selector
<ul id="images">
2). bind fancybox to all <a>
anchors that are children of your #images
element, like
var fancyGallery = $("#images").find("a"); // we cache the selector here fancyGallery.attr("rel","gallery").fancybox({ type: "image" });
notice that we add the rel
attribute on the fly to all anchors so that they are part of the same gallery
3). attach the click
event to the button
(I would recommend that you give it an ID
too, so that in the future it does not get messed up with other possible buttons), which runs the existing fancybox script, as described above, so with this html
<button id="fancyLaunch">Launch Fancybox</button>
use this script
$('#fancyLaunch').on('click', function() { fancyGallery.eq(0).click();
notice that we used the .eq()
method to launch the gallery from the first element (first index
in javascript is always 0)
To summarize, your whole script might look like this:
jQuery(document).ready(function($) { var fancyGallery = $("#images").find("a"); fancyGallery.attr("rel","gallery").fancybox({ type: "image" }); $('#fancyLaunch').on('click', function() { fancyGallery.eq(0).click(); }); });
See JSFIDDLE
source share