Reputation: 163
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>'
});
Upvotes: 1
Views: 123
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>';
}
});
Upvotes: 1
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>'
}));
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!'));
Upvotes: 3