Accurate calculation for determining the position of a popup when hovering the mouse

My aim is to display a popup when hovering over a grid. The question I have is, how can I position the popup at the center from the top and left for each grid. Could someone please help me modify the code below to calculate the correct offset (left & top)? In the plunker code provided below, the result is not as expected. Thank you for any assistance.

Check out the PLUNKER URL

Here is the code snippet:

$(document).ready(function(){
  $("ul.listing li").each(function(i){
            var offset = $(this).offset();
            console.log("index->" +i + "<-index " +"left - "+ offset.left+ "<br/> top - "+offset.top);
                $(this).hover(function() {
                    $(".popupContainer").hide();
                    $(".popupContainer").fadeIn(200).html($(this).html()).css({'left': offset.left/3, 'top': offset.top});
                    $(".popupContainer").hover(function(){
                        $(".popupContainer").show();    
                    }, function(){
                        $(".popupContainer").hide();
                    });
                }, function() {
                    $(".popupContainer").hide();
                });
        });
});

Answer №1

Have you considered attempting the following approach? https://plnkr.co/edit/a9zkLP?p=preview

Here is a sample of JavaScript:

$(document).ready(function(){
    $("ul.listing li").each(function(i){
        var pop = $('<div class="popupContainer"></div>').html($(this).html());
        $(this).append(pop);
    })
});

And here is an example of CSS:

ul.listing li{
  position: relative;
}

.popupContainer{
    position: absolute;
    transform:translate(-50%,-50%);
    top:0;
    left:0;
  }
  ul.listing li:hover .popupContainer{display: block;}

Answer №2

To utilize element properties such as offsetLeft, offsetTop, offsetWidth, and offsetHeight.

$(document).ready(function(){
    $("ul.listing li").each(function(i){
        $(this).hover(function() {
            var offsetleft = this.offsetLeft;
            var offsettop = this.offsetTop;
            $(".popupContainer").hide();
            $(".popupContainer").fadeIn(200).html($(this).html()).css({'left': offsetleft - this.offsetWidth/2, 'top': offsettop - this.offsetHeight*1.3});
            $(".popupContainer").hover(function(){
                  $(".popupContainer").show();  
                }, function(){
                  $(".popupContainer").hide();
                });
                }, function() {
                    $(".popupContainer").hide();
                });
        });
});

Additionally, include a few extra pixels for proper alignment.

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

Using Vuex in the router: A comprehensive guide

I am having trouble accessing data from the store in the router. I have attempted three different methods, but none of them seem to be working correctly. Here are the methods I tried: // ReferenceError: store is not defined console.log(store.state); // ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

What is the best way to use regular expressions in JavaScript to pull out a date value from a string?

I am working with a string in this format: var value = "/Date(1454187600000+0300)/". From this, I need to extract a date format like 1/30/2016. Currently, I have the following code snippet: var value = "/Date(1454187600000+0300)/"; // I need to extract f ...

Experiencing an overwhelming number of re-renders due to a specialized React Hook

I have been fetching data from a Neo4J database using the use-neo4j library and developed a custom hook for this purpose. The hook executes a query to retrieve the data from the database and then formats it in a way that enables me to visualize the data ef ...

An index problem with BufferGeometry

Trying to transition code from openFrameworks to THREE.JS for generating a landscape with Perlin noise. The approach involves creating a static index array first, followed by positioning vertices in a square grid, each offset by a specific distance. This s ...

What is the best way to separate a string using JQuery?

My menu contains PNG icons. I am looking to achieve a hover effect where the PNG icon changes to a GIF icon when the user hovers over a menu item. I've attempted the following: jsFiddle $("#image").mouseenter(function(){ // I can set GIF url her ...

The typeface displayed is Rubik Light Font instead of the regular Rubik font

I am currently working on incorporating the Rubik Font into my project: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> < ...

What is the best way to update an object within a deeply nested array of objects using lodash?

I am facing a challenge in my React JS application where I have an array of objects that I need to dynamically modify. Here is the structure of my array : sections: [ { id: 'e9904688-fd8a-476d-8f46-930bc4d888d1', ...

Retrieve distinct keys from a JSON file in Node.js

Below is an example of JSON data: [ { "Name": "User1", "primaryRegion": "US" }, { "Name": "user2", "primaryRegion": "US" }, { "Name": &q ...

What is the best method to extract text data from the Froala editor?

Currently, my method involves using $('div#edit').froalaEditor('html.get') to get the HTML data from the editor. Unfortunately, this process becomes problematic when trying to process or store the text data in my backend due to the pres ...

Unveiling the mystery behind the inner workings of the (function(){

Hello everyone, I'm fairly new to programming and trying to wrap my head around a confusing method. var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(call ...

Tips on how to align a wrapper-div in the center without affecting the positioning of the

I am looking to keep my page perfectly centered in the browser without affecting the content (similar to how align-text: center works). Specifically, I want to center my wrapper-div. How can I achieve this? Here is a simplified version of my current page ...

Combining various data entries within a unified form

I have a requirement to create a user-friendly page for entering multiple sets of personal information. Users should be able to fill out details for each record separately and then submit all the records at once. My goal is to design the page in such a wa ...

Challenges with Tab navigation in React and Ionic 5

I am facing a challenge with getting the tabs navigation to function correctly. Here is my current code: App.tsx: const App: React.FC = () => <IonApp> <IonReactRouter> <IonRouterOutlet id="main"> < ...

Solving issues with the autocomplete feature in typeahead search through ajax calls

Currently, I am setting up a text input to function as a search box for retrieving search results through ajax calls with the assistance of the bootstrap typeahead plugin <form class="form-inline ml-3" action="/phone-autocomplete/"&g ...

During the build process, the parameters in Next.js are not accessible

I am currently using Next.js 13 with the experimental app directory. My application utilizes dynamic routing in the following format: https://app.domain/[itemid]/[slug] Within my [slug] directory, if I create a server-side route file pages.jsx with th ...

The text box in HTML5 is too wide due to excessive padding

I need to update my input field to be padded from the inside as I transition to HTML5. It was working fine in HTML 4.01 Transitional, but now it overflows outside of the table frame in HTML5. Can someone help me fix this for HTML? Snippet of HTML Code &l ...

What is the best way to remove data from both arrays simultaneously?

I am working with a grid that displays a list of time ranges. For example: timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}] time=[{Value:12:00:00 id:10} {Value:14:00:00 id:100} ...