The excellent and rather flexible jQuery plugin FancyBox has become my defacto jQuery lightbox implementation and as such it has found its way into most of my project work.
One of the cool little tricks I stumbled across was the ability to dynamically alter the URL of an iframe loading fancybox implementation and thought it a good idea to share over here.
In my example I have a number of rows, all with a distinct record id and all which need an edit functionality.
Now what I do is I have a single edit script which gets called via iframe load by a fancybox click on the edit icon at the end of each row. The trick here is of course that the edit page being loaded needs to know which row to edit, and thus I want to pass this bit of vital information on to the loaded edit script.
To do this I capture the record id in the tag attribute of my edit image and then create a click handler to fire when any of the edit images are clicked upon. In my javascript section of code, I create an empty anchor tag which I then apply fancybox to in the usual manner, specifying of course that the anchor tag is of an iframe class and that it should load the base URL of my edit script.
Okay, so by now you’ve realized that instead of applying fancybox to each edit image like one would normally do, I’ve gone and simplified things by applying it to only one, unused and unseen element on the page. The final part of this trickery thus now lies in the click event handler attached to each of the edit images.
What we basically do is on click, grab the tag attribute of the clicked item (which contains the id of the record to be edited) and then use this value to alter the href attribute of our already fancyboxed anchor element, basically adding a GET variable to the edit script URL.
With this set, you simply trigger a click event on the anchor tag and presto, you now have a dynamic iframe fancybox loader! :)
So to get an idea of what the code would look like:
<img style=”cursor:pointer;” class=”edit-audit-image” tag=”ID134″ src=”images/b_edit.png”>
<img style=”cursor:pointer;” class=”edit-audit-image” tag=”ID263″ src=”images/b_edit.png”>
<div style=”display:none;”><a id=”edit-audit-fancybox” class=”iframe” href=”admin_edit_audit.php” title=”Edit Existing Audit”> </a></div>
//fancybox the hidden anchor tag
$("a#edit-audit-fancybox").fancybox({ 'hideOnContentClick': true, 'enableEscapeButton': true, 'frameHeight' : 600 });
//fire when an edit image is clicked
$('.edit-audit-image').click(function(){
//append the tag of the clicked image to the end of the edit script URL
$("a#edit-audit-fancybox").attr('href','admin_edit_audit.php?id=' + ($(this).attr('tag')))
//force a launch of the fancybox
$("a#edit-audit-fancybox").click();
});
Nifty.
Related Link: http://www.fancybox.net/