Search code examples
javascriptjquerycssbootstrap-4tooltip

Why doesn't the style of the bootstrap tooltip show?


I am trying to style text in a bootstrap tooltip. My request is rather simple: I want the tooltip text on the first button to appear in red. I use the

data-html="true"

to use HTML in my tooltip. Why isn't it red?

<button data-toggle="tooltip" data-html="true" data-trigger="click" title="<div style='color:red;'>this text should be red</div>">
    Press me
</button>

On the same matter, I want the tooltip on the following tooltip to show in the first place. The table environment hides it completely. Is this the same problem?

<button data-toggle="tooltip" data-html="true" data-trigger="click" title="<table><tr><td>this text should appear</td></tr></table>">
    Press me 2
</button>

I created a fiddle that shows the problem clearly.

https://jsfiddle.net/ws9z37q2/9/

Any help would be highly appreciated. Thanks in advance!


Solution

  • Give a class to the element and apply the style to the class in CSS.

    $(function() {
      $('[data-toggle="tooltip"]').tooltip()
    })
    .red {
      color: red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
    
    
    <button data-toggle="tooltip" data-html="true" data-trigger="click" title="<div class='red'>this text should be red</div>">
      Press me
    </button>


    When I checked the source code of Bootstrap in Github by default it's sanitizing the HTML content the style attribute is not allowed, check here for more info.

    So alternately you can make it works by disabling sanitize option(Not recommented).

    $(function() {
      $('[data-toggle="tooltip"]').tooltip({
        sanitize: false
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
    
    
    <button data-toggle="tooltip" data-html="true" data-trigger="click" title="<div style='color:red'>this text should be red</div>">
      Press me
    </button>