Developing a hovercard/tooltip feature

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!

Answer №1

Once I move the mouse away from the link, the hover effect vanishes along with the link itself

The event listener is set to detect mouseenter on an a element. Within the listener, the following code is executed:

$(this).focus().addClass('hov');

This assigns the hov class to the a element (this). Subsequently, in the mouseleave code, the following is done:

$(".hov").hide();

Consequently, the a element gets hidden.

I'm uncertain about how to implement the hov styling exclusively when hovering over a link leading to a user's profile rather than any random link

You can use a distinct class on the link and then define styles for that specific class.


Consider trying something similar to this approach (refer to comments within the code):

$(function(){
    // attach the event listener directly to the element
    // note that we've given the element a class
    $('a.student')
    .on('mouseenter', function(){
        data = "foo";
        // ensure to display the tooltip element
        $(".hov").html("<span>" + data + "</span>").show();
    })
    .on('mouseleave', function(){
        setTimeout(function(){
            // hide the tooltip element after a couple of seconds
            $(".hov").hide();
        }, 2000);                           
    });
});
.hov {
  /* make sure this is hidden initially */
  display: none;
  position: relative;
 }

.hov span {
  height: 150px;
  width: 250px;
  white-space: nowrap;
  /* if the parent div is hidden, this will be hidden as well; no need to specify display property */
  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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="hov">

</div>

<p>
    <a class="student">A link!</a>
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to incorporate an ajax response into my form without the need for a separate javascript file?

I have a basic form for submissions that I want to convert to an Ajax form. This way, the user won't be redirected to the thanks.php page after submitting. Instead, I would like the response from thanks.php to be displayed within the specified div. C ...

How can I modify the container to prevent the Bootstrap dropdown from being clipped by overflow:hidden settings?

With bootstrap, I encountered a situation where dropdown menus are being clipped by my <div> with overflow: hidden. How can I address this issue without incurring high costs? One potential solution might be to change the container of all dropdowns wi ...

Building a Modal in React and Triggering it for Display, followed by Making an AJAX Request upon Submission

Check out my CodePen snippet (minus delete ajax request): http://codepen.io/martincarlin87/pen/KzPWOw I've been diving into the world of React recently, and I'm working on converting a page in my web application to utilize React instead of just ...

Transforming color images into black and white using JavaScript

     I have implemented this code to convert colored images to grayscale. function applyGrayscaleEffect() {         var imageData = contextSrc.getImageData(0, 0, width, height);         var data = imageData.data;         var p1 = 0.99;   ...

Ways to retrieve the user's IP address and provide the information in JSON format

Although I am not an expert in PHP, I specialize in developing Android apps. One of the challenges I face is extracting the user's IP address from a specific URL . This URL provides various information when accessed, but my main requirement is to retr ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...

How can the results of an AJAX JSON request be effectively showcased?

When I make a call via ajax to an api, what is the simplest way to display the result? If I use alert on the result, I only see [object object]. If I try to alert a specific item that I know is in the returned JSON (results.title, for example), I get an &a ...

Implementing jQuery in ASP.NET code-behind files

I am new to asp.net and trying to learn by experimenting with rendering aspx in only specific parts. I was able to make it work, but encountered an issue when trying to create a button, textbox, and label where the label would display the text from the tex ...

Utilizing Fullcalendar v5's sticky header feature alongside a Bootstrap fixed top navigation bar for a seamless

Currently experimenting with the latest version of fullcalendar 5.4.0. I have integrated the calendar into a bootstrap 4 web page that features a fixed navigation bar at the top. The issue arises when attempting to set stickyHeaderDates, aiming to keep th ...

Is it possible to send an array through an ajax URL?

Is it possible to pass a PHP array as a URL parameter using the GET method? My PHP array looks like this: Array ( [0] => 4 [1] => 5 ) To achieve this, I first convert it into an AngularJS array by doing the following: $scope.myData.excludeList = &a ...

Looking to create an anchor tag that navigates to a specific ID on the page while accommodating a fixed header placement

In my application, the homepage's carousel displays multiple images with dynamically generated anchor tags that link to different routes. When clicking on the anchor tag, the page scrolls to the linked image but is obstructed by a fixed header. I want ...

fetching the name of the button from a servlet on a JSP page

I am currently working on a project in eclipse using JSP. I am facing an issue with detecting which button is pressed when submitting a form with an ajax call. The request.getParameter(button-name) method is returning null within the doPost method of the s ...

Working with HTML5 Canvas to Clip Images

Is there a way to implement a tileset image in canvas like this one? I am trying to figure out how to make it so that clicking on the first tile returns 0, clicking on the tenth tile returns 9, and so on... Any suggestions on how to clip a tileset on an ...

Tips on deobfuscating Next.js HTML from online sources

I am faced with the task of reconstructing a website that I scraped from the internet using wget. It seems to be built on next js, based on the presence of the _next folder. Even though I have no experience with nextjs and do not understand its inner worki ...

Incorporating a separate PHP file which includes JavaScript code

I've been struggling to make this code work. In my footer file, I have the following: footer.php: <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url: '', type: 'GET', dataType: "script", success: ...

Troubleshooting: My Bootstrap collapse navbar refuses to cooperate

Hi there! I'm working on creating a responsive navbar with Bootstrap, but I'm having trouble getting the collapse feature to work. Can someone please assist me? Here are the lines of code I have: <nav class="navbar navbar-expand-md navba ...

The output of PHP is not being captured by Ajax

I have a JavaScript code that calls a PHP script to retrieve a value, but it's not working as expected. Here is my JavaScript code: $.ajax({ type: 'GET', url: '/home/example.com/ftp/www/typo3conf/ext/quiz_rs/pi1', data ...

Creating a dynamic hover drop-down navigation bar in ASP.NET

After successfully creating a navigation bar with hover effects, I am now looking to implement a dropdown list when hovering over the items. Can anyone provide guidance on how to achieve this? Below is the current code snippet I am working with: <ul c ...

Can combinators be applied to select elements containing options?

How can I use a select dropdown menu to toggle the appearance of a text input field? Specifically, when the option with a value of '4' is chosen, the text input should become visible. Here is the code snippet: HTML <div class="paren ...

Get JSON in Sync

Objective: My goal is to retrieve data from the database and refresh the main.php page (specifically through draw_polygon) each time new information is added to the database (post $.ajax submission to submit_to_db.php). Essentially, I have a main.php file ...