Unusual occurrences when using absolute positioning, style.top, style.left, and the HTML "a" tag

Struggling to complete a task on Javascript.info involving an "a" tag. The objective is simple - place (and remove) a tooltip above the element upon hover. No issues with positioning over the roof or house, but as soon as I try to place the box above the link, it breaks and seems unsolvable.

Asking for assistance here since the solution provided uses position:fixed while attempting to use position:absolute instead. Merely copying the solution doesn't contribute to learning. The trouble arises on line 77 and 78, specifically while assigning tooltip.style.left and tooltip.style.top.

If assigned with a literal value (e.g., "-58px"), it works as expected. Anything else reverts to the default of the tooltip on "house." Tried debugging with tactical alerts, only ended up confused. It appears using a computed value causes defaults, whereas a literal functions correctly.

Seeking an explanation for this behavior along with insights (correction on understanding position:absolute, element size properties, or similar).

The script code below modified from line 64 onwards (rest credits to original authors):

<!DOCTYPE HTML>
<html>

<head>
...
      // Script Code Modified Here
    house.onmouseover= function(event){
      let target= event.target.closest('[data-tooltip]');

      let tooltip= document.createElement('div');
      tooltip.textContent= target.dataset.tooltip;
      tooltip.classList.add("tooltip");
      target.append(tooltip);

      if(!tooltip.parentElement.style.position){
        tooltip.parentElement.style.position= 'relative';
      }
      tooltip.style.position= 'absolute';
      tooltip.style.top= "-"+(tooltip.offsetHeight+5)+"px";
      tooltip.style.left= -target.clientLeft+(target.offsetWidth-tooltip.offsetWidth)/2+"px";
      
      //alert("-"+(tooltip.offsetHeight+5)+"px");
      //alert(tooltip.style.top);
    }
    house.onmouseout= function(event){
      let target= event.target.closest('[data-tooltip]');
      tooltips= target.querySelectorAll('.tooltip');
      for(tooltip of tooltips){
        tooltip.remove();
      }
    }
  </script>


<body>
  
  ...
    
</body>
</html>

Appreciate any help! :)

Answer №1

Whenever I attempt to position the box above the link, it ends up breaking

This issue arises because the tooltip box is set to display below the mouse cursor. When hovering over the link, it triggers a continuous loop of events:

  1. Creating and adding the tooltip element to the <a> element
  2. The mouse hovers over the tooltip element
  3. mouseout event is triggered on the a element in preparation for mouseover on the tooltip
  4. mouseout handling removes the tooltip element
  5. The mouse then moves back over the a element
  6. mouseover event is fired on the a element, repeating the cycle from step 1.

The problem does not occur during roof or interior mouseover events because the tooltip box is positioned outside the target element with the data-tooltip attribute.

To address this issue, you could:

  1. Reposition the tooltip box so that it does not appear directly under the mouse
  2. Find creative ways to utilize mouseenter and mouseleave events on the anchor element that do not trigger when hovering over the tooltip (as it is a child of the anchor)
  3. Disable pointer events on tooltip elements:
.tooltip { 
    pointer-events: none; 
}

Additional listeners were added to investigate the problem further:

house.addEventListener("mouseover", e=>console.log("over"));
house.removeEventListener("mouseout", e=>console.log("out"));

Introducing the logging function did introduce a slight delay, leading to the tooltip box being rendered and visible in Firefox. The output from the log confirms the existence of the feedback loop.

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

Trouble with HTML and CSS design layout

I'm struggling to create a responsive design for my webpage. The layout should consist of black blocks that display images. Ensuring the layout adapts to different screen sizes is proving challenging. It needs to maintain its shape on smaller screens ...

When clicking, populate the content of another div in a vertical top-to-bottom fashion

I am in the process of creating a functionality where clicking on one element will fill another element's content from bottom to top. Although I have managed to make it work on hover, the same functionality is not triggered when clicking on the eleme ...

AngularJS controller exceeding allowed complexity (SonarLint alert)

While utilizing SonarLint in Eclipse, I encountered an issue while working on an AngularJS application. Specifically, I was cleaning up a controller to improve readability when SonarLint flagged the following problem: The function has a complexity of 11 ...

Can an event be activated when a field in HTML5 is deemed valid?

Valid fields in HTML5 follow specific conventions, such as an type="email" needing to adhere to the email format. CSS provides a way to select valid fields using the pseudo-element: input:valid. Can we set up an event that triggers when the input becomes ...

Enhancing websites with CSS3 and VueJS for fluid and captivating background gradients transitions

After implementing a logic in the application, the gradient is now changing dynamically. <template> <div :style="`background-image: ${backgroundImage}`" class="background"> <snackbar /> <nuxt /> <default-footer /&g ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

I need the table to have a customized sorting order when it first loads, utilizing the tablesorter functionality

When my page loads, I have a table that looks like this: https://i.sstatic.net/Z4tli.png However, I want the subjects to be in a specific order (math, history, science, and physics), while sorting the professor names in ascending order. https://i.sstatic. ...

Retrieving PHP information using Javascript and storing it in an array

I have a PHP script that fetches data from a server and stores it in an array. I then convert this array into a JSON object using the following function: echo json_encode($result); Now I want to access this array in my JavaScript and display it. I want t ...

Obtain the value or values of radio buttons based on certain conditions

Recently, I have been delving into .JS and grappling with pre-existing code. One of the challenges I face involves extracting data from radio buttons after a particular selection is made. The gist of it is related to transportation requirements. Upon indi ...

Using PHP and MySQL to create checkboxes populated with data retrieved from a database, and then submitting two parameters

Hey there, I've been struggling with this issue for quite some time. I'm trying to create a list with checkboxes populated from a database that includes [checkbox of car id and value][brand][model]. The goal is to select two cars from the list, ...

Choose the element that is trapped within the div

I've hit a roadblock with this issue that I just can't seem to figure out. I was working on a practice project creating a Netflix-like webpage, and the select element in the footer containing languages is stuck and won't budge. Here's m ...

Impact of designs on the elements within components

Here's a CSS query I have: If I have the code below, does the styling apply to the contents of v-container but not v-container itself? <v-app id="inspire"> <v-container justify-center style="max-width: 1200px"> <v-layout row ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

There is an issue with the JSON format being received by fetch in JS when using json_encode in php

Recently, I encountered an issue with my JavaScript function that retrieves data from a PHP page. In the JS code block: fetch("print.php) .then(function (r) { return r.json() }) .then(function (values) { ...... ...... ...

Sharing information between pages in React through Router

I am struggling to transfer a single string from one page to another using react router and only functional components. I have created a button that links my pages, but I can't seem to pass the string successfully. Here is an example of the code on th ...

Personalizing the success message of a function in node.js

I received this node.js code for an IBM Cloud function that allows a user of my Watson Assistant to send me email reminders. It's working flawlessly. var nodemailer = require('nodemailer'); let smtpConfig = { host: 'hosthere', ...

Tips for sorting on an ANTD table with a JSON array column instead of a string

I am facing an issue with filtering and searching in an antd table. The table has 2 columns, and I want to filter on the first column and search text on the second one. After rendering the application, everything seems fine. However, there is a problem re ...

Looking for a simple method to generate a text-only dropdown link in Bootstrap 4 without using a button?

Is there a simple method to create a text-only dropdown link in Bootstrap 4 without using a button? Or do I have to adjust the padding and buttons using CSS to make the "Delivery" dropdown blend in with the rest of the text? I've searched online and ...

The PHP Include function seems to be malfunctioning and unable to properly display

Everything you see is what I have on my home.php page <?php include ('../bgs/bg-verbier.html'); include('../menus/menu-verbier.html'); ?> Both of the files requested are located in the parent directory. The /menus/menu-v ...

"Enhance your Magento store with the ability to showcase multiple configurable products on the category page, even when dropdown values are not

As I work on adding multiple configurable products to a category list page in Magento 1.7.2, I am facing some challenges due to using the Organic Internet SCP extension and EM Gala Colorswatches. While following tutorials from various sources like Inchoo a ...