dogpunk
dogpunk

Reputation: 163

Is it possible to make multiple Bootstrap popovers more DRY?

I've run into a problem, where I have more than 10 popovers in one table. They all should display a popover on hover, and have a similar html, but with some differences in content. I made it the easiest way, but I feel there must be a smarter way to do this.

Is it possible to make this js code more DRY?

 $('#static-pop-1').popover({
        'trigger': 'hover',
        'placement': 'bottom',
        'html': true,
        'content': '<div class="static-popover"><span>Hey!</span></div>'
    });

 $('#static-pop-2').popover({
        'trigger': 'hover',
        'placement': 'bottom',
        'html': true,
        'content': '<div class="static-popover"><span>Hey 2!</span></div>'
    });

http://jsfiddle.net/axt63orn/

Upvotes: 1

Views: 123

Answers (2)

Artur Filipiak
Artur Filipiak

Reputation: 9157

You could use data attribute:

<a class="pop" id="static-pop-1" data-mycontent="Hey 1!" title="">Content 1</a>

$('.pop').popover({
    'trigger': 'hover',
    'placement': 'bottom',
    'html': true,
    'content': function(){
        return '<div class="static-popover"><span>'+$(this).data('mycontent')+'</span></div>';
    }
});

JSFiddle

Upvotes: 1

adeneo
adeneo

Reputation: 318252

Assuming you don't want the popover to just say Hey 1, Hey 2 etc. but actually set a different content in each, but keep the rest of the settings the same, you can do

var settings = {
    trigger   : 'hover',
    placement : 'bottom',
    html      : true
}

$('#static-pop-1').popover($.extend({}, settings, {
    content: '<div class="static-popover"><span>Hey!</span></div>'
}));

$('#static-pop-2').popover($.extend({}, settings, {
    content: '<div class="static-popover"><span>Hey 2!</span></div>'
}));

$('#static-pop-3').popover($.extend({}, settings, {
    content: '<div class="static-popover"><span>Hey 3!</span></div>'
}));

FIDDLE

or you could use a function

function setting(text) {
    return {
        trigger   : 'hover',
        placement : 'bottom',
        html      : true,
        content   : '<div class="static-popover"><span>'+text+'</span></div>'
    }
}

$('#static-pop-1').popover(setting('Hey!'));
$('#static-pop-2').popover(setting('Hey 2!'));
$('#static-pop-3').popover(setting('Hey 3!'));

FIDDLE

Upvotes: 3

Related Questions