Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every time. How can I achieve this?
$(document).ready(function() {
$('.tooltipTarget').click(function() {
var title = $(this).data('tooltip');
if (!$('p.tooltip').hasClass('active')) {
$('<p class="tooltip active"></p>')
.text(title)
.appendTo($(this));
$('.tooltip').addClass('test');
$(document).on('click', function(e) {
if (e.target != $('.tooltipTarget')[0]) {
$('.tooltipTarget').trigger('click');
}
});
} else {
$(document).off('click');
$('p.tooltip.active').fadeOut(250, function() {
$(this).remove();
});
}
});
});
.tooltip {
margin-top: -45px;
opacity: 1;
transition: 0.3s ease-in-out;
position: absolute;
border-radius: 1px;
color: #767676;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
background: #f7f7f7;
padding: 10px;
font-size: 12px;
text-align: left;
z-index: 10;
max-width: 250px;
&.active {
opacity: 1;
}
}
.tooltip::before {
content: '';
display: inline-block;
height: 0;
width: 0;
position: absolute;
z-index: 10;
bottom: -14px;
right: 50%;
right: calc(50% - 7px);
border-left: solid 7px transparent;
border-right: solid 7px transparent;
border-bottom: solid 7px transparent;
border-top: solid 7px #f7f7f7;
}
.tooltip::after {
content: '';
display: inline-block;
height: 0;
width: 0;
position: absolute;
z-index: 9;
bottom: -15px;
right: 50%;
right: calc(50% - 7px);
border-left: solid 7px transparent;
border-right: solid 7px transparent;
border-bottom: solid 7px transparent;
border-top: solid 7px rgba(0, 0, 0, 0.2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>CSS3 tooltip</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<button style="margin: 200px;" data-tooltip="This is a tooltipThis is a ltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tootooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is his is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is his is a tooltipThis is a tooltipThis is a tooltipThis is a tooltipThis is his is a tooltipThis is a tooltipThis is a tooltipThistooltipThis is a tooltip"
class="tooltipTarget">orempaks[djo[psad</button>
</body>
</html>
P.S. I prefer not to rely on the basic HTML title functionality.