I'm trying to create a hovercard for a social network project. The idea is that when you hover over some user's name, a HC will appear containing some more info about that user. When you move your mouse away, it will disappear after 2 seconds.
Here's my code. First, I have an empty div with a class of hov
that will contain the info.
<div class="hov">
</div>
Here's my jquery script:
$(function(){
$('body').on('mouseenter', 'a', function(){
let username = $(this).attr('href');
let quotesname = JSON.stringify(username);
let name = JSON.parse(quotesname)
// on the live site this span is populated by an Ajax call
data = "foo";
$(".hov").html("<span>" + data + "</span>");
$(this).focus().addClass('hov');
}).on('mouseleave', 'a', function(){
setTimeout(function(){
$(".hov").hide();
}, 2000);
});
});
(All of the above is in the header file, which is included in all other files)
And finally, here's the CSS:
.hov {
position: relative;
}
.hov span {
display: none;
height: 150px;
width: 250px;
white-space: nowrap;
}
.hov:focus span {
display:block;
position:absolute;
padding: 0.2em 0.6em;
border:1px solid #996633;
border-radius: 5px;
background-color: grey !important;
color:#fff;
z-index: 100;
}
My idea was to detect using jquery when someone is hovering over a link. Then it would extract the href
part and send it to the php response file, which would check if the href
part matches any of the usernames in the database. If it does, it would send the info about that user that would be displayed in the HC (if a link contains a user's name, it's always the link to that user's profile). If it doesn't, it won't send anything and then no HC will be displayed (that's why I used the if(data)
condition inside the ajax part). I managed to make the HC appear when you hover over a username, along with the info sent from the php response file; however I face two problems that I can't solve, no matter how hard I try.
1) When I remove the mouse from the link, the HC disappears, but so does the link I hovered over (no matter if it's a text, picture..whatever it was, it's gone). I tried all sorts of things in the mouseleave
part (detect if the div is not in focus, remove or detach the div, remove the class, remove the class attribute from the hov
, etc), but with no result. That's why I have that line $(".hov").hide();
there, it's the best I could get so far. I suspect that it has something with removing the hov
class completely when you move your mouse away, I really can't tell.
2) I'm not sure how to apply the hov
styling only when I hover over a link to a user's profile, and not some random link. I created the ajax call for that very purpose, to see if a link is to a user or not, but I'm not sure if and how I can use the same logic to solve this.
Any help would be much appreciated,
Thanks!