Bootstrap 4 Tooltip Styling for Dynamic Elements

by nsmcan

HTML

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<h1>Test tooltip styling</h1>
<div><span title="Long-long-long tooltip doesn't fit the single line">Hover over me 1</span></div>
<div><span data-tooltip-custom-classes="tooltip-left" data-container="body" title="Example (left aligned):<br>Tooltip doesn't fit the single line, and is not a sibling">Hover over me 2</span></div>
<div><span class="text-danger" data-tooltip-custom-classes="tooltip-large tooltip-left tooltip-danger" title="Example (left aligned):<br>This long text we want to have in the single line">Hover over me 3</span></div>

CSS

/* CSS used here will be applied after bootstrap.css */
.tooltip.tooltip-large > .tooltip-inner {
    max-width: 350px;
}

.tooltip.tooltip-left > .tooltip-inner {
    text-align: left;
}

.tooltip.top.tooltip-danger > .tooltip-arrow {
  border-top-color: #d9534f;
}
.tooltip.top-left.tooltip-danger > .tooltip-arrow {
  border-top-color: #d9534f;
}
.tooltip.top-right.tooltip-danger > .tooltip-arrow {
  border-top-color:#d9534f;
}
.tooltip.right.tooltip-danger > .tooltip-arrow {
  border-right-color: #d9534f;
}
.tooltip.left.tooltip-danger > .tooltip-arrow {
  border-left-color: #d9534f;
}
.tooltip.bottom.tooltip-danger > .tooltip-arrow {
  border-bottom-color: #d9534f;
}
.tooltip.bottom-left.tooltip-danger > .tooltip-arrow {
  border-bottom-color: #d9534f;
}
.tooltip.bottom-right.tooltip-danger > .tooltip-arrow {
  border-bottom-color: #d9534f;
}
.tooltip.tooltip-danger > .tooltip-inner {
  background-color: #d9534f;
}

JavaScript

$(document).on('inserted.bs.tooltip', function(e) {
    var tooltip = $(e.target).data('bs.tooltip');
    $(tooltip.tip).addClass($(e.target).data('tooltip-custom-classes'));
});

$('body').tooltip({ 
    selector: "[title]", 
    html: true
});