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

The process of toggling a div to slide up and down explained

I'm attempting to create a slide toggle effect on a hidden DIV when a user hovers over specific link buttons. JavaScript: $(function () { // DOM ready shorthand var $content = $(".sliderText"); var $contentdiv = $(".sliderCo ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

Modify the NAME attribute when clicked using Jquery

I am attempting to modify the NAME attribute of a DIV with the text from a textbox using jQuery. Take a look at my code snippet: http://jsfiddle.net/e6kCH/ Can anyone help me troubleshoot this issue? ...

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

Guide to implementing a universal animated background with Angular components

I'm having trouble figuring out why, but every time I attempt to use a specific code (for example: https://codepen.io/plavookac/pen/QMwObb), when applying it to my index.html file (the main one), it ends up displaying on top of my content and makes ev ...

How can I convert a JSON template to HTML using AngularJS?

As someone who is just starting out with AngularJS, I am facing an issue where the HTML tags in a JSON file are not being encoded when rendered in HTML using AngularJS. Is there a specific method in AngularJS that can help with this? This is what my HTML ...

An additional "?" symbol found in the PHP file at the top left corner

I am experiencing an issue with a PHP page where a "?>" symbol appears in the top left corner. The code snippet looks like this: <?php include_once("DBconnect.php"); $getuser = $_POST["RegUsername"]; $getpass = $_POST["Pass"]; $getrepass = $_POST["ReP ...

Enabling block scrolling on a parent element using jscrollpane functionality

Is it possible to set up a jscrollpane so that the parent pane doesn't scroll when the child scroll has reached its bottom? Currently, when the child scrolling reaches the bottom, the parent also scrolls. I would like the parent to only scroll when th ...

Utilize custom fonts from your local directory within a Vite Vue3 project

Inside my main.scss file, I am loading local fonts from the assets/styles/fonts folder: @font-face { font-family: 'Opensans-Bold'; font-style: normal; src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truety ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

Preloading error alert message displayed during AJAX request

When I send an ajax request with a dropdown change, the loader div is shown using "before send". However, the issue is that the loader only displays for the first time, even though the ajax functionality works all the time. If you want to check this issue ...

Utilize Fullpage.js afterSlideLoad event to repeat animations across multiple slides

Can anyone help me figure out what I'm doing wrong here? I'm trying to apply my slide animations to each slide without having to manually copy and paste for each index. The console log is working for every slide except for the first one (0), bu ...

When pasting Arabic text into an input box, the words in HTML appear to be jumbled and shuffled around

When I replicate this text يف عام and input it into a box, the output is shown as follows عام يف ...

What is the best way to ensure that my website functions properly on Safari mobile?

I successfully created a website that functions well on my computer across all modern browsers. However, a user reported that it is not working on Safari mobile. Upon testing the website on Safari for Windows, it appeared to display correctly. After view ...

What causes the html5 <audio> tag to appear differently on Chrome versus IE browsers?

When viewed in Chrome, the design appears clean and compact, but when seen in Internet Explorer, it looks large and overwhelming. Check out the screenshots below.. Do you have any suggestions to fix this issue? Know of any mp3 hosting platforms with an emb ...

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

Adjusting the width of a div element using a button

I am currently diving into the world of JavaScript, React, and Node.js. My current challenge involves attempting to adjust the width of a div element using a button. However, I keep encountering the same frustrating error message stating "Cannot read prope ...

Obtaining iframe contents post request using jQuery

I'm attempting to send a submission to an iframe and receive a response. Check out my code on Jsfiddle test.php currently just sends back 'abcd' for testing purposes. I would like to capture this response - simply alert it out for now. Fi ...

What is the best way to merge variable name in AngularJS?

How to combine variable name in HTML code: app.controller example $scope.name ='abc'; $scope.abc123 = response.data; HTML example <h1>{{name}}</h1> <h1>{{{{name}}123}}</h1> <!-- I want the value of abc ...