How to create a direct link to any fancybox box

First you still need to have links to your images in the page that opens fancybox like:

<a id="image01" class="fancylink" rel="gallery" href="https://stackoverflow.com/questions/9028310/images/01.jpg" title="image 01">open image 01</a>
<a id="image02" class="fancylink" rel="gallery" href="images/02.jpg" title="image 02">open image 02</a>

… etc.

Notice that I am adding both an ID and a class to each anchor since the only way I have to target them via URL is through their ID … the class will be used to open those images in fancybox in a regular way once I am on the page so I don’t need to write a specific fancybox code for each ID.

then set this script on the page of reference:

<script type="text/javascript">
var thisHash = window.location.hash;
$(document).ready(function() {
 if(window.location.hash) {
  $(thisHash).fancybox().trigger('click');
 }
 $('.fancylink').fancybox();
}); // ready
</script>

then you can provide the URL that targets each image like

http://mydomain.com/page.html#image01

or

http://mydomain.com/page.html#image02

etc.

wanna working demo?

http://picssel.com/playground/jquery/targetByID_28jan12.html#image01

http://picssel.com/playground/jquery/targetByID_28jan12.html#image02

NOTE: This code is for fancybox v1.3.x since you used fancybox.net as reference.

UPDATE #1: if you want fancybox options you need to add them in both selectors ID and class like:

<script type="text/javascript">
var thisHash = window.location.hash;
$(document).ready(function() {
 if(window.location.hash) {
  $(thisHash).fancybox({
    padding: 0
    // more API options
  }).trigger('click');
 }
 $('.fancylink').fancybox({
    padding: 0
    // more API options
 });
}); // ready
</script>

Of course, use the right options either for fancybox v1.3.x or 2.x

Leave a Comment