Explain Codes LogoExplain Codes Logo

Jquery UI tooltip does not support html content

javascript
jquery
tooltip
xss
Alex KataevbyAlex Kataev·Dec 8, 2024
TLDR

Pop some HTML into your jQuery UI tooltips using the content option, by returning your HTML string directly or fetching the title attribute:

$(".selector").tooltip({ content: function() { return "<strong>Welcome</strong> to the <em>tooltips</em> revolution!"; } });

This piece of brilliance will inject HTML text into tooltips of elements rocking the .selector class. Your key to tooltips freedom now supports HTML!

To keep the users safe, be sure to escape the HTML by sanitizing it against XSS attacks:

$(".selector").tooltip({ content: function() { // We're escaping HTML, just like Houdini! return $("<div>").text(this.getAttribute("title")).html(); } });

Stealth mode: Undercover functionality

Unlocking tooltip treasure

An upgrade to jQuery 1.9.1 and jQueryUI 1.10.2 are in order to amp up the tooltip game. Make a call on jQuery and jQueryUI compatibility before enabling HTML content. Use data-tooltip attribute if you prefer to fly under the radar and not mess with the default browser behavior:

$(".selector").tooltip({ content: function() { // Just like unlocking secret levels in a game! return $(this).data("tooltip"); } });

Securing your gold mine

Beware of XSS attacks, they lurk in every corner! Ensure the HTML content is as pure as gold by sanitization. Use functions like jQuery.text() or libraries like DOMPurify to escape the content.

Commandeering tooltip widgets

Need to flex your coding muscles? Override the tooltip .widget():

$.widget("custom.enhancedTooltip", $.ui.tooltip, { _create: function() { this._super(); // /*insert superhero theme song*/ }, _setOption: function(key, value) { if (key === "content" && typeof value === "string") { // Payday! We're escaping! value = this._escapeHtml(value); } this._super(key, value); }, _escapeHtml: function(string) { // Excape room for strings, you've got 60 seconds to escape! } }); $(".selector").enhancedTooltip();

The total e-mc2 for dynamic content

For tooltips that are dynamic like a chameleon, use a function:

$(".selector").tooltip({ content: function() { // You're a wizard Harry! Creating tooltips from thin air! return "<div class='tooltip-content'>" + $(this).data('dynamicContent') + "</div>"; } });

Fashion guide for tooltips

Control your tooltip's appearance using CSS for .ui-tooltip. Bedazzle your tooltips!

Practical examples: The Coding Colosseum

Test your tooltips. Make sure they hold the fort in different browser wars!