Open In App

How to Hide the Default Title When Using a Tooltip in JavaScript?

Last Updated : 20 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The default browser tooltip is shown when a user hovers over an element with a title attribute. To hide this default title, you can use JavaScript to temporarily remove the title attribute while still implementing your custom tooltip.

1. Temporarily Remove the Title Attribute

This method removes the title attribute on hover and restores it once the mouse leaves the element. During this time, a custom tooltip is shown near the cursor.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
	<style>
		.custom-tooltip {
			display: none;
			position: absolute;
			background-color: #333;
			color: white;
			padding: 5px;
			border-radius: 3px;
			font-size: 12px;
			pointer-events: none;
			z-index: 10;
		}
	</style>
</head>
<body>
	<div class="tooltip-element" title="This is the default tooltip">Hover over me</div>
	<div class="custom-tooltip" id="customTooltip"></div>
	<script>
		const tooltipElements = document.querySelectorAll('[title]');
		const customTooltip = document.getElementById('customTooltip');
		tooltipElements.forEach(element => {
			element.addEventListener('mouseover', function () {
				const originalTitle = this.getAttribute('title');
				this.setAttribute('data-original-title', originalTitle);
				this.removeAttribute('title');
				customTooltip.innerText = originalTitle;
				customTooltip.style.display = 'block';
				element.addEventListener('mousemove', function (e) {
					customTooltip.style.top = `${e.pageY + 10}px`;
					customTooltip.style.left = `${e.pageX + 10}px`;
				});
			});
			element.addEventListener('mouseout', function () {
				this.setAttribute('title', this.getAttribute('data-original-title'));
				customTooltip.style.display = 'none';
			});
		});
	</script>
</body>
</html>

2. Replace the Title with a Custom Tooltip

In this approach, the title attribute is completely removed, and a custom tooltip is displayed using the data-tooltip attribute. This method relies on CSS to show the tooltip.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Custom Tooltip</title>
	<style>
		.tooltip-element {
			display: inline-block;
			position: relative;
			cursor: pointer;
		}
		.tooltip-element:hover::after {
			content: attr(data-tooltip);
			position: absolute;
			top: 100%;
			left: 50%;
			transform: translateX(-50%);
			background-color: #333;
			color: white;
			padding: 5px;
			border-radius: 3px;
			font-size: 12px;
			white-space: nowrap;
		}
	</style>
</head>
<body>
	<div class="tooltip-element" data-tooltip="This is a custom tooltip">Hover over me</div>
</body>
</html>

Next Article
Article Tags :

Similar Reads