I'm trying to add a tooltip to table rows based on data fetched via an AJAX request. The goal is to display additional info when the user hovers over a row in a specific table. Here’s the code I’m currently using:
function tooltip(event) {
const sor = event.target.closest('tr');
if (!sor) return;
const tabla = sor.closest('table');
const tablaNev = tabla.id.replace('Tabla', '');
console.log(tablaNev);
const mezo = Array.from(sor.children).map((cella) => cella.innerText);
console.log(mezo);
if (tablaNev === "tablazat0") {
const id = mezo[0];
$.get(`/bevetel?id=${id}`, function(data) {
if (data && data.length > 0) {
const osszesDarab = data[0].OsszesDarab;
const osszesBevetel = data[0].OsszesBevetel;
$(sor).attr(
"title",
`Összes darab: ${osszesDarab}, Összes bevétel: ${osszesBevetel} Ft`
);
}
});
}
}
$(document).on('mouseover', '#tablazat0 tbody tr', tooltip);
<div class="row col-12 justify-content-center" style="height: calc(100vh - 100px);">
<div class="col-lg-5 h-100 mb-5" style="overflow: auto;">
<h2 id="tablazatCim0" class="tablazatCim"></h2>
<table id="tablazat0" class="table table-striped table-bordered table-hover table-responsive-xs">
<thead id="tablazatHead0"></thead>
<tbody id="tablazatBody0"></tbody>
</table>
</div>
<div class="col-lg-5 h-100 mb-5" style="overflow: auto;">
<h2 id="tablazatCim1" class="tablazatCim"></h2>
<table id="tablazat1" class="table table-striped table-bordered table-hover table-responsive-xs">
<thead id="tablazatHead1"></thead>
<tbody id="tablazatBody1"></tbody>
</table>
</div>
</div>
It mostly works, but sometimes the tooltip doesn't appear unless I move the mouse away and back again. I assume this is because the title attribute is added after the initial mouseover.
Question: How can I ensure the tooltip appears immediately after the AJAX call sets the title? Is there a better way to dynamically update tooltips like this using jQuery?
Any suggestions or improvements are welcome. Thanks in advance!