Bootstrap Text Overflow Tooltip

by Talsja

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="row">
  <div class="truncate col-sm-1">
  Lorem ipsum dolor sit amet, consectetur
  </div>
  <div class="truncate col-sm-1">
  ちょっと長い文字列が表示されたら
  </div>
</div>


<!-- HTML to write -->
<a href="#" data-bs-toggle="tooltip" title="Some tooltip text!">Hover over me</a>

<!-- Generated markup by the plugin -->
<div class="tooltip bs-tooltip-top fade show bs-tooltip-bottom" role="tooltip">
  <div class="tooltip-arrow"></div>
  <div class="tooltip-inner">
    Some tooltip text!
  </div>
</div>

SCSS

.truncate {
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}


.tooltip{
	text-align:left;
}

JavaScript

$.fn.tooltipOnOverflow = function (options) {
        $(this).on("mouseenter", function () {

            if (this.offsetWidth < this.scrollWidth) {
                options = options || { placement: "bottom", tooltipClass: 'tooltip-white' };
                options.title = $(this).text();

                $(this).tooltip(options);
                $(this).tooltip("show");
            } else {
                if ($(this).data("bs.tooltip")) {
                    $(this).tooltip('hide');
                    $.removeData("bs.tooltip");
                }
            }
        });
    };


$('.truncate').tooltipOnOverflow();