Fancybox dynamic image load from var


Fancybox dynamic image load from var



I am using this code to grab a class value from an a href:


<a href="" class="images/success.jpg">Click to get image</a>

<script>
$("#myMenu a").bind("click", function() {
var myPic = $(this).attr("class");
alert(myPic);
});
</script>



Everything working normal and smooth. Now I am using fancybox to load images and I have this code of fancy box that works normal also:


$.fancybox.open('images/success.jpg');



I am trying to pass the variable myPic into fancybox code but I cant make it.



So far I have tried this:


$.fancybox.open(myPic);
$.fancybox.open('myPic');



Is there any possibility to make it work?




1 Answer
1



There are always easier or more complicated ways to achieve the same result. Having a class="images/success.jpg" is not semantically appropriate. The easiest way to do it is to have that inside the href attribute like :


class="images/success.jpg"


href


<a class="fancybox" href="images/success.jpg">Click to get image</a>



... and use the class to bind fancybox like


class


$(".fancybox").fancybox();



... that will also make sure that your link is accessible regardless if javascript is enabled or not (and more SEO friendly too.)



However, you may have your own reasons (I hope) to pass the ref through a variable or through a different attribute (class in your example). To make your code neater, you may rather prefer to use a (HTML5) data-* attribute like :


class


data-*


<a href="#nogo" data-path="images/success.jpg">Click to get image</a>



... and get the value of the data-path attribute without requiring to set a variable and pass it to fancybox like :


data-path


$("#menu a").on("click", function() {
$.fancybox.open($(this).data("path"));
});​



Notice the use of jQuery .on() method that requires jQuery 1.7+


.on()



See this FIDDLE for both working examples





Thanks JFK.. Works Great!
– George L.
Nov 18 '12 at 10:30






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter