user3733831
user3733831

Reputation: 2926

How I create this jquery in a reusable way?

I am using Bootstrap popovers with dynamic contents from my databese. In php, its creating dynamic classes for each popover. My question is, In jquery, do I need to call to triggering the popover separately?

This is how I use jQuery to trigger the popovers -

$(".image-info-popover-1").popover({
        html : true, 
        placement : 'left',
        trigger: 'hover',
        content: function() {
            return $('.popoverContent-1').html();
        },
        title: function() {
            return $('.popoverTitle-1').html();
        }
}); 

$(".image-info-popover-2").popover({
        html : true, 
        placement : 'left',
        trigger: 'hover',
        content: function() {
            return $('.popoverContent-2').html();
        },
        title: function() {
            return $('.popoverTitle-2').html();
        }
});

$(".image-info-popover-3").popover({
        html : true, 
        placement : 'left',
        trigger: 'hover',
        content: function() {
            return $('.popoverContent-3').html();
        },
        title: function() {
            return $('.popoverTitle-3').html();
        }
}); 

$(".image-info-popover-4").popover({
        html : true, 
        placement : 'left',
        trigger: 'hover',
        content: function() {
            return $('.popoverContent-4').html();
        },
        title: function() {
            return $('.popoverTitle-4').html();
        }
}); 

$(".image-info-popover-5").popover({
        html : true, 
        placement : 'left',
        trigger: 'hover',
        content: function() {
            return $('.popoverContent-5').html();
        },
        title: function() {
            return $('.popoverTitle-5').html();
        }
}); 

But this is not the best way If I have a list of popovers to triggering out. So anybody tell me the good way to do this in a reusable manner?

Thank you.

Upvotes: 1

Views: 83

Answers (1)

michaelpri
michaelpri

Reputation: 3651

If you want it be reusable, I'd put it in a function which takes a number as a parameter. Your function could look like this

var popover_func = function(n) {
    $(".image-info-popover-"+n).popover({
        html : true, 
        placement : 'left',
        trigger: 'hover',
        content: function() {
            return $('.popoverContent-'+n).html();
        },
        title: function() {
            return $('.popoverTitle-'+n).html();
        }
    });
};

You should be able to call this using a for-loop

for (var i=0; i<=5;i++) {
    $(document).ready(popover_func(i));
}

Upvotes: 3

Related Questions