
The term tooltip does not have a unique translation into English, it can be described as "tooltip", "help balloon", "pop-up description" or even "help text" depending on the context in which it is used.
A tooltip is a pop-up message that appears when interacting with an element, either by clicking on it or by hovering the mouse. These tooltips are used to provide additional information without taking up permanent space. Ideal for explaining icons, technical terms or actions in interfaces.
Do tooltips harm or benefit SEO?
Well, as for almost everything, the answer is always it depends. While SEO purists warn that Google does not like "hidden" or masked content and penalises its use harshly, this would be an extreme for cases of abuse that could "cannibalise" your content. However, tooltips, used with a certain balance and a minimum of logic, can be beneficial.
Advantages of using tooltips
Broadly speaking, these messages, if friendly and unobtrusive, can contribute to improving different aspects of the user experience. Among other things, they reduce bounce rates and improve accessibility. It can also provide opportunities to use additional keywords that do not naturally fit into the main content, which helps with semantic SEO.
In addition, they can improve click-through rates. By offering tooltips in the navigation or call-to-action buttons, they can guide users more effectively, leading to higher click-through rates. But for all of this to be possible, a few minimum guidelines must be followed.
Recommendations for appearance, content and operation
- Use of HTML elements and ARIA attributes to ensure that screen readers and search engines can access the information they contain.
- A tooltip must be brief. Obviously, no one is going to read a huge amount of information in a pop-up and you will be covering a large part of the content. It should contain the minimum, precise and necessary information, and this should not be critical for the user when carrying out or completing any action.
- Content should not be redundant or repeated, make sure that you are providing additional useful and necessary information and that it is not repeated in your content to avoid "duplicate content".
- Try to avoid as much as possible tooltips that disappear when you move the cursor or use them only in messages that do not contain a lot of information and/or content. Ideally, they should be displayed per click and close when you click again anywhere on the screen.
- Make sure they are legible and of the correct size.
- Don't add twenty different designs of tooltip icons or tooltip links, that only creates confusion. A fixed and consistent design will help your visitors identify them at first glance.
- Don't overdo it, plan your strategy well to add them only where you think they facilitate access to relevant and/or necessary complementary information.
Features and functionalities of the code
This .png image with transparent background has been used for this case.
Here you can test the final result working [tooltip text="Example tooltip used in jrmora.com" position="auto"].
The URL of the image is added between the single quotes on this line:
$default_image = 'URL-de-tu-imagen';
If you choose to modify the code to use an SVG HTML icon, like this one, you will be able to play with the colour, background, thickness, etc. more easily.
Intelligent automatic position adjustment to avoid screen edges. I.e. when approaching the top edge, the tooltip is displayed at the bottom and vivecersa.
Fully functional links can be added within the tooltip with customisable styles. While it is not advisable to add links, it is possible that you may need to do so on occasion. In the event that a tooltip contains a link there is a 200ms delay in automatic hiding to make it easier to click.
Secure HTML support. Supports:
<strong>, <em>, <a>, <br>, <span>
Position, fixed and adaptable attributes.
Atributos de posición disponibles: position="auto" (default), top, bottom, left, right
ARIA attributes (aria-expanded, role="tooltip").
Responsive design.
Mobile adaptable (clickable toggle).
Resetting when resizing, rotating or shifting
Main CSS classes:
.tooltip-container /* Contenedor principal */
.tooltip-trigger /* Botón/icono que activa el tooltip */
.tooltip /* Caja del mensaje emergente */
.tooltip-arrow /* Flecha indicadora */
Key functions of the JS:
calculateBestPosition() // Determina si colocar el tooltip arriba, abajo, etc.
showTooltip() // Muestra el tooltip
hideTooltip() // Oculta el tooltip con retraso
Examples of shortcodes:
[tooltip text="Texto a mostrar"]
[tooltip text="Texto a mostrar <strong>en negrita</strong> donde sea" position="auto"]
[tooltip text="Texto <strong>importante</strong> y <em>énfasis</em>"]
[tooltip text="<a href='https://ejemplo.com' target='_blank'>Visite nuestro sitio</a>"]
This code is the one I have used for my specific needs. Understand it as a starting point. It is very improvable. You can separate the CSS and the JS (or even consider it without using Javascript) and adapt it so that it can also be applied to words in the content without showing the icon.
To use it, as always, just add it to the functions.php of your template or your child theme if you want to keep the changes when your template is updated.
Code
/**
* Shortcode para tooltip con ajuste automático
* Un ejemplo de uso: [tooltip text="Texto <a href='#'>enlace</a>" position="auto"]
*/
function custom_tooltip_shortcode($atts) {
$default_image = 'URL-de-tu-imagen';
$atts = shortcode_atts(
array(
'text' => __('Información adicional', 'text-domain'),
'position' => 'auto',
'color' => '#6a0000',
'shadow' => '#9c9c9c',
'width' => '18px',
'id' => 'tooltip-' . uniqid()
),
$atts,
'tooltip'
);
// HTML permitido
$allowed_html = array(
'strong' => array(),
'b' => array(),
'em' => array(),
'i' => array(),
'br' => array(),
'span' => array(
'style' => array(),
'class' => array()
),
'a' => array(
'href' => array(),
'title' => array(),
'target' => array(),
'style' => array(),
'rel' => array()
)
);
$text = wp_kses($atts['text'], $allowed_html);
$position = in_array($atts['position'], ['top', 'bottom', 'left', 'right', 'auto']) ? $atts['position'] : 'auto';
$color = sanitize_hex_color($atts['color']);
$shadow = sanitize_hex_color($atts['shadow']);
$width = esc_attr($atts['width']);
$id = sanitize_html_class($atts['id']);
$output = '
<span class="tooltip-container" data-position="' . esc_attr($position) . '">
<button class="tooltip-trigger" aria-describedby="' . $id . '" aria-expanded="false">
<img src="' . esc_url($default_image) . '" width="' . $width . '" alt="" aria-hidden="true"/>
</button>
<span id="' . $id . '" role="tooltip" class="tooltip" style="background-color: ' . $color . '; box-shadow: 0 5px 10px ' . $shadow . ';">
' . $text . '
<span class="tooltip-arrow"></span>
</span>
</span>';
return $output;
}
add_shortcode('tooltip', 'custom_tooltip_shortcode');
/**
* Estilos CSS optimizados para enlaces
*/
function add_tooltip_styles() {
echo '
<style>
.tooltip-container {
display: inline-block;
position: relative;
vertical-align: middle;
}
.tooltip-trigger {
background: none;
border: none;
padding: 0;
margin: 0 2px;
cursor: pointer;
line-height: 1;
}
.tooltip {
position: absolute;
color: #fff;
padding: 10px 12px;
border-radius: 4px;
font-size: 14px;
line-height: 1.5;
width: 220px;
max-width: 90vw;
text-align: left;
visibility: hidden;
opacity: 0;
transition: opacity 0.25s ease;
z-index: 100000;
pointer-events: none;
}
.tooltip a {
color: #fff !important;
text-decoration: underline;
pointer-events: auto !important;
}
.tooltip * {
pointer-events: auto;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border: 7px solid transparent;
}
/* Posiciones dinámicas */
.tooltip[data-position="top"] {
bottom: 100%;
left: 50%;
transform: translateX(-50%);
margin-bottom: 10px;
}
.tooltip[data-position="top"] .tooltip-arrow {
top: 100%;
left: 50%;
transform: translateX(-50%);
border-top-color: inherit;
}
.tooltip[data-position="bottom"] {
top: 100%;
left: 50%;
transform: translateX(-50%);
margin-top: 10px;
}
.tooltip[data-position="bottom"] .tooltip-arrow {
bottom: 100%;
left: 50%;
transform: translateX(-50%);
border-bottom-color: inherit;
}
.tooltip[data-position="left"] {
top: 50%;
right: 100%;
transform: translateY(-50%);
margin-right: 10px;
}
.tooltip[data-position="left"] .tooltip-arrow {
top: 50%;
right: 0;
transform: translate(50%, -50%);
border-left-color: inherit;
}
.tooltip[data-position="right"] {
top: 50%;
left: 100%;
transform: translateY(-50%);
margin-left: 10px;
}
.tooltip[data-position="right"] .tooltip-arrow {
top: 50%;
left: 0;
transform: translate(-50%, -50%);
border-right-color: inherit;
}
/* Interacción */
.tooltip-trigger:hover + .tooltip,
.tooltip-trigger:focus + .tooltip,
.tooltip-trigger[aria-expanded="true"] + .tooltip {
visibility: visible;
opacity: 1;
}
</style>
';
}
add_action('wp_head', 'add_tooltip_styles');
/**
* JavaScript corregido para enlaces clickeables con retraso
*/
function add_tooltip_scripts() {
echo '
<script>
document.addEventListener("DOMContentLoaded", function() {
// Configurar todos los tooltips
document.querySelectorAll(".tooltip-container").forEach(function(container) {
const tooltip = container.querySelector(".tooltip");
const trigger = container.querySelector(".tooltip-trigger");
let hoverTimeout;
let isMouseInTooltip = false;
const position = container.getAttribute("data-position");
// Función para calcular posición automática
function calculateBestPosition() {
const rect = trigger.getBoundingClientRect();
const viewportHeight = window.innerHeight;
const viewportWidth = window.innerWidth;
const tooltipHeight = 150; // Altura estimada
const tooltipWidth = 220; // Ancho estimado
const space = {
top: rect.top,
bottom: viewportHeight - rect.bottom,
left: rect.left,
right: viewportWidth - rect.right
};
// Determinar mejor posición disponible
if (space.top >= tooltipHeight || (space.top >= space.bottom && space.top > 50)) {
return "top";
} else if (space.bottom >= tooltipHeight) {
return "bottom";
} else if (space.right >= tooltipWidth) {
return "right";
} else if (space.left >= tooltipWidth) {
return "left";
}
return "top"; // Default
}
// Actualizar posición (solo para "auto")
function updatePosition() {
if (position === "auto") {
tooltip.setAttribute("data-position", calculateBestPosition());
}
}
// Mostrar tooltip
function showTooltip() {
clearTimeout(hoverTimeout);
tooltip.style.visibility = "visible";
tooltip.style.opacity = "1";
trigger.setAttribute("aria-expanded", "true");
}
// Ocultar tooltip con retraso de 200ms
function hideTooltip() {
if (!isMouseInTooltip) {
hoverTimeout = setTimeout(() => {
tooltip.style.visibility = "hidden";
tooltip.style.opacity = "0";
trigger.setAttribute("aria-expanded", "false");
}, 200); // Retraso clave para enlaces
}
}
// Inicializar posición
updatePosition();
// Eventos para el botón
trigger.addEventListener("mouseenter", showTooltip);
trigger.addEventListener("mouseleave", hideTooltip);
trigger.addEventListener("focus", showTooltip);
trigger.addEventListener("blur", hideTooltip);
// Eventos para el tooltip (mejorados para enlaces)
tooltip.addEventListener("mouseenter", function() {
isMouseInTooltip = true;
clearTimeout(hoverTimeout); // Cancelar ocultamiento
});
tooltip.addEventListener("mouseleave", function() {
isMouseInTooltip = false;
hideTooltip(); // Iniciar retraso para ocultar
});
// Click en el botón (para móviles)
trigger.addEventListener("click", function(e) {
e.preventDefault();
if (tooltip.style.visibility === "visible") {
hideTooltip();
} else {
showTooltip();
}
});
// Reajustar posición en eventos
if (position === "auto") {
window.addEventListener("resize", updatePosition);
window.addEventListener("scroll", updatePosition, { passive: true });
}
});
// Cerrar tooltips al hacer clic fuera (excepto en enlaces)
document.addEventListener("click", function(e) {
if (!e.target.closest(".tooltip-container") && !e.target.closest(".tooltip a")) {
document.querySelectorAll(".tooltip").forEach(function(tooltip) {
tooltip.style.visibility = "hidden";
tooltip.style.opacity = "0";
});
document.querySelectorAll(".tooltip-trigger").forEach(function(trigger) {
trigger.setAttribute("aria-expanded", "false");
});
}
});
});
</script>
';
}
add_action('wp_footer', 'add_tooltip_scripts');