Automatically add fancybox class to image links

Stevan
Stevan
Member
310 Points
20 Posts

I'm using the tinymce html editor to add dynamic content including images with img tags. I want to add fancy box to open image in large view popup.
What I want is for all the images to automatically be associated with FancyBox without having to add the code manually.

Basically content has images something like this:

<img src="image.jpg">

I'm trying something like this:

$("img").fancybox({
            'type': 'image',
            'overlayShow': false,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic'
        });
Views: 3074
Total Answered: 2
Total Marked As Answer: 1
Posted On: 14-Sep-2019 23:53

Share:   fb twitter linkedin
Answers
Alice
Alice
Member
32 Points
1 Posts
         

To fancybox you needed to wrap img with anchor tag after that fancy box will work. Either you can use server side logic to wrap with anchor or you can use following jquery script on client side:

$('img').each(function () {
    $(this).wrap($('<a/>', {
        href: $(this).attr('src'),
        class: "fancybox",
        rel: "fancyimage"
    }));
});

Then use following:

$("a[rel=fancyimage]").fancybox({
            'type': 'image',
            'overlayShow': false,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic'
        });
Posted On: 15-Sep-2019 06:18
sid
sid
Member
120 Points
9 Posts
         

There is another way, for images, to automatically can be associated with FancyBox without even need to wrap - .wrap() - them with an anchor. A different approach would be to link them directly to fancybox on click like :

$(document).ready(function () {
    $("img")
        .css("cursor", "pointer")
        .on("click", function(){
            $.fancybox($(this).attr("src"),{
                'type': 'image',
                'overlayShow': false,
                'transitionIn': 'elastic',
                'transitionOut': 'elastic'
            });
        });
});  

In this way, it does not process anything until the actual image is clicked. This would be better in terms of performance (consider 200+ images being wrapped every page load).

Posted On: 17-Sep-2019 08:00
 Log In to Chat