I'm currently working on developing a hovercard feature for a social media platform I'm building. The concept involves displaying additional information about a user when their name is hovered over. The hovercard will appear with the user's details, and then disappear after 2 seconds once the mouse moves away.
Here is an outline of my approach: First, I have created an empty div with the class hov
to serve as the container for the information.
<div class="hov">
</div>
Next, I have implemented a 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);
});
});
(The above code snippet resides in the header file, which is included in all other files)
Lastly, here is the CSS styling:
.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;
}
The main objective is to utilize jQuery to detect when someone hovers over a link, extract the href
section, and send it to a PHP response file. This file would verify if the URL corresponds to any usernames in the database. If there is a match, the relevant user information is sent back to be displayed in the hovercard (as links to profiles always contain usernames). If no match is found, no information is sent, and consequently, no hovercard is presented. To manage this logic, I employed an if(data)
condition within the ajax process. While the hovercard successfully appears when hovering over a username, two persistent issues remain unresolved despite numerous attempts.
1) Removing the mouse from the link causes both the hovercard and the original link to disappear unexpectedly. Various adjustments were made within the mouseleave
action without success. As a temporary solution, I utilized $(".hov").hide();
, although it remains unsatisfactory. Suspicions point towards potential removal conflicts between mouse movements and the hov
class.
2) Ensuring that the hov
styling only applies when hovering over user profile links, rather than random links, presents a challenge. Although an ajax call was constructed for this purpose, integrating similar logic poses uncertainties regarding implementation methods.
I welcome any assistance or guidance in resolving these obstacles,
Thank you!