Lightbox To Ajax Images
Hey all, This tutorial is for the problem that occurs, when lightbox doesn’t work with images called with ajax.
The problem usually occurs when you are using many javascript frameworks together. Since i faced one, so felt it to share with you all.
The tutorial is simple and easy to implement. The trick is to load lighbox.js with jQuery when you want it.
Here is the simple code.
code for index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <title>Using lightbox with ajax</title> <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" /> <script type="text/javascript" src="js/jquery.js"></script> <script src="js/prototype.js" type="text/javascript"></script> <script src="js/scriptaculous.js?load=effects,builder" type="text/javascript"></script> <script src="js/lightbox.js" type="text/javascript"></script> <style type="text/css"> body{ color: #333; font: 13px 'Lucida Grande', Verdana, sans-serif; } #update { margin-top: 10px; } #update a img { border: #202020 3px solid; } </style> </head> <body> <h1>Using <a href="http://www.lokeshdhakar.com/projects/lightbox2/">Lightbox JS <em>with ajax</em></a></h1> <p><a href="http://www.lokeshdhakar.com">by Harpreet BHatia</a></p> <h2>Example</h2> <select name="imageOption" id="imgOptn"> <option value="xxx">----Select Image Type-----</option> <option value="1">Type 1</option> <option value="2">Type 2</option> </select> <script type="text/javascript"> jQuery("[name=imageOption]").change(function() { //------loading lightbox script using jquery----- jQuery.getScript("js/lightbox.js", function() { cat = jQuery('[name=imageOption]').val(); if(cat != "xxx") { var dataString = 'cat=' + cat; { jQuery("#flash").show(); jQuery("#flash").fadeIn(400).html('<span>Loading Image, Please wait...</span>'); //----calling the php file to get images ------ jQuery.ajax( { type: "POST", url: "getImages.php", data: dataString, cache: false, success: function(html) { { jQuery("#update").empty(); jQuery("#update"). append(html); jQuery("#update").fadeIn("slow"); jQuery("#flash").hide(); //jQuery("#update").fadeOut(7000); } } }); return false; } } else { jQuery("#update").fadeOut(); } }); }); </script> <div id="flash"></div> <div id="update"> </div> </body> </html>
Code for php file
<?php $t = $_POST['cat']; if($t == 1) { ?> <a href="images/hat_big.jpg" rel="lightbox[roadtrip]"> <img src="images/hat.jpg" width="200" height="200" alt="" /> </a> <a href="images/glow_big.jpg" rel="lightbox[roadtrip]"> <img src="images/glow.jpg" width="200" height="200" alt="" /> </a> <? } else { ?> <a href="images/roof_big.jpg" rel="lightbox"> <img src="images/roof.jpg" width="200" height="200" alt="" /> </a> <? } ?>
View Demo
Hope you like it…
Tags: ajax, Demo, images, javascript, JQuery, lightbox, problem, solution
