How to make fancybox href dynamic?

I have the following fancybox code:

$('.fancybox').fancybox({ 'autoScale' : false, 'href' : $('.fancybox').attr('id'), 'type':'iframe', 'padding' : 0, 'closeClick' : false, //some other callbacks etc 

the problem is that I have twenty different tag tags on the page and I want the fancybox href attribute to take the identifier of the clicked element, i.e. the one that raised the event.

I tried several things, none of them work!

 'href' : $(this).attr('id'), 'href' : $(this.element).attr('id'), 

It seems so simple, but anytime I plug in 'this' or nothing like that works.

+6
source share
5 answers

Without each() or click() just add the beforeLoad to your script, like this

 $(".fancybox").fancybox({ autoScale: false, // href : $('.fancybox').attr('id'), // don't need this type: 'iframe', padding: 0, closeClick: false, // other options beforeLoad: function () { var url = $(this.element).attr("id"); this.href = url } }); // fancybox 

NOTE : this is for fancybox v2.0.6 +

On the other hand, a more elegant solution should use the (HTML5) data-* attribute to set href (it would be strange to set id="images/01.jpg" otherwise) so that you can do:

 <a href="#" id="id01" data-href="images/01.jpg" ... 

and your callback

 beforeLoad: function(){ var url= $(this.element).data("href"); this.href = url } 

and use the id attribute for what is intended for.


EDIT . It is best to use the special data-fancybox-href attribute in your anchor, for example:

 <a id="item01" data-fancybox-href="http://jsfiddle.net" class="fancybox" rel="gallery" href="javascript:;">jsfiddle</a> 

and use a simple script without a callback like

 $(".fancybox").fancybox({ // API options autoScale: false, type: 'iframe', padding: 0, closeClick: false }); 

See JSFIDDLE

+29
source

You can .fancybox over your collection of .fancybox elements and grab the id.

 $('.fancybox').each(function(){ $(this).fancybox({ 'autoScale' : false, 'href' : $(this).attr('id'), 'type':'iframe', 'padding' : 0, 'closeClick' : false, //some other callbacks etc }); }); 
+4
source

Try the following:

 $(".fancybox").click(function(){ var url = $(this).attr('id'); $.fancybox({ 'autoScale' : false, 'href' : url , 'type':'iframe', 'padding' : 0, 'closeClick' : false, //some other callbacks etc }); }) 
+3
source

try it

 $('.fancybox').each( function() { var elem = jQuery(this); elem.fancybox({ 'autoScale' : false, 'href' : elem.attr('id'), 'type':'iframe', 'padding' : 0, 'closeClick' : false, }); } ); 
+1
source

Have you tried this?

 $('.fancybox').each(function(){ $(this).fancybox({ 'autoScale' : false, 'href' : this.id, 'type':'iframe', 'padding' : 0, 'closeClick' : false, //some other callbacks etc }); }); 
+1
source

Source: https://habr.com/ru/post/921148/


All Articles