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 thehrefattribute like :… and use the
classto bind fancybox like… 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 (
classin your example). To make your code neater, you may rather prefer to use a (HTML5)data-*attribute like :… and get the value of the
data-pathattribute without requiring to set a variable and pass it to fancybox like :Notice the use of jQuery
.on()method that requires jQuery 1.7+See this FIDDLE for both working examples