Custom jQuery Tooltip
by jay prakash
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom jQuery Tooltip</title>
<link rel="stylesheet" href="styles.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button class="tooltip-btn" data-tooltip="This is a custom tooltip!">Hover Me</button>
<button class="tooltip-btn" data-tooltip="Another tooltip example!">Hover Again</button>
<div id="tooltip"></div>
<script src="script.js"></script>
</body>
</html>
CSS
#tooltip {
position: absolute;
background: rgba(0, 0, 0, 0.8);
color: #fff;
padding: 8px 12px;
border-radius: 5px;
font-size: 14px;
display: none;
white-space: nowrap;
pointer-events: none;
}
.tooltip-btn {
margin: 20px;
padding: 10px 20px;
background: #007bff;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
}
#tooltip {
transform: scale(0);
transition: transform 0.2s ease-out, opacity 0.2s ease-out;
}
#tooltip.show {
transform: scale(1);
opacity: 1;
}
JavaScript
$(document).ready(function () {
$(".tooltip-btn").hover(function (event) {
let tooltipText = $(this).attr("data-tooltip");
$("#tooltip").text(tooltipText).fadeIn(200);
}, function () {
$("#tooltip").fadeOut(200);
});
$(".tooltip-btn").mousemove(function (event) {
$("#tooltip").css({
top: event.pageY + 10 + "px",
left: event.pageX + 10 + "px"
});
});
$(".tooltip-btn").hover(function () {
let tooltipText = $(this).attr("data-tooltip");
$("#tooltip").text(tooltipText).addClass("show");
}, function () {
$("#tooltip").removeClass("show");
});
});