"Akıllı" tooltip
Kullanıcı fareyle bir elementin üzerinden geçtiÄinde ancak üzerinden geçip gitmediÄinde tooltip (ipucu) gösteren bir fonksiyon yazın.
DiÄer kelimelerle, eÄer kullanıcı faresiyle bir ögenin üzerine gelirse ve durursa â tooltipi göster. Ancak eÄer faresiyle bu ögenin üzerinden hızlıca geçip giderse, tooltip gösterme.
Teknik olarak, bir öÄenin üzerindeki fare hızını ölçebiliriz, eÄer hızı yavaÅsa biz bunu elementin üzerinden geçiyor kabul ederek tooltipi göstermeliyiz. Hızı fazla ise o zaman görmezden gelmeliyiz.
Bunun için global obje new HoverIntent(options) yap. options (seçenekler) ile beraber:
elemâ Takip edilecek element.overâ EÄer fare elementin üzerinden yavaÅca geçiyorsa çaÄırılacak fonksiyon.outâ Fare elementin üzerinden ayrıldıÄı zaman çaÄırılacak fonksiyon (eÄeroverçaÄırıldıysa).
Tooltip için böyle bir objeyi kullanmaya bir örnek:
// örnek tooltip
let tooltip = document.createElement('div');
tooltip.className = "tooltip";
tooltip.innerHTML = "Tooltip";
// mouse hareketlerini takip edecek nesne
new HoverIntent({
elem,
over() {
tooltip.style.left = elem.getBoundingClientRect().left + 'px';
tooltip.style.top = elem.getBoundingClientRect().bottom + 5 + 'px';
document.body.append(tooltip);
},
out() {
tooltip.remove();
}
});
demo:
Fareyi âsaatâ üzerine hızlı bir Åekilde hareket ettirirseniz hiçbir Åey olmaz ve bunu yavaÅ yaparsanız veya durdurursanız, bir tooltip gösterecektir.
Lütfen dikkat: imleç saat alt öÄeleri arasında hareket ettiÄinde tooltip âgelip gitmezâ.
The algorithm looks simple:
- Put
onmouseover/outhandlers on the element. Also can useonmouseenter/leavehere, but they are less universal, wonât work if we introduce delegation. - When a mouse cursor entered the element, start measuring the speed on
mousemove. - If the speed is slow, then run
over. - Later if weâre out of the element, and
overwas executed, runout.
The question is: âHow to measure the speed?â
The first idea would be: to run our function every 100ms and measure the distance between previous and new coordinates. If itâs small, then the speed is small.
Unfortunately, thereâs no way to get âcurrent mouse coordinatesâ in JavaScript. Thereâs no function like getCurrentMouseCoordinates().
The only way to get coordinates is to listen to mouse events, like mousemove.
So we can set a handler on mousemove to track coordinates and remember them. Then we can compare them, once per 100ms.
P.S. Please note: the solution tests use dispatchEvent to see if the tooltip works right.