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?
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 :
<a class="fancybox" href="images/success.jpg">Click to get image</a>
... and use the class
to bind fancybox like
$(".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 :
<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 :
$("#menu a").on("click", function() {
$.fancybox.open($(this).data("path"));
});
Notice the use of jQuery .on()
method that requires jQuery 1.7+
See this FIDDLE for both working examples