Is it possible to design an element that only becomes visible when another element is hovered over and then moves along with the cursor?

Objective

In this project, the main goal is to create two interactive elements: element A and element B. The desired outcome is for element B to only appear when element A is hovered over, while also smoothly following the cursor without any jittering.

Individually, I have successfully implemented the hovering/showing functionality and the smooth cursor-following behavior. However, I am facing challenges in integrating these two features seamlessly without introducing any jitter caused by offsetX/offsetY properties.

Implementation

UPDATE:

The code snippet provided below may not execute correctly; it is recommended to copy the code into a file for accurate testing.

HTML Code:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="content">
      <div id="A"></div>
      <div id="B"></div>
    </div>
  </body>
  <script src="script.js"></script>
</html>

CSS Styling:

* {
 margin: 10px;
}

#content {
  position: absolute; 
  border: 5px solid green;
}

#A {
  border: 5px solid red;
  width: 500px;
  height: 500px;
}

#B {
  display: none;
  position: absolute;
  border: 5px solid blue;
  width: 100px;
  height: 100px;
}

#A:hover~#B {
  display: block;
}

JavaScript Implementation:

let b = document.getElementById('B');

const onMouseMove = (e) =>{
  b.style.left = e.offsetX + 'px';
  b.style.top = e.offsetY + 'px';
}

document.addEventListener('mousemove', onMouseMove);

Description

This setup involves placing both elements A and B inside the "content" division. Moving either of them out of this setting will disrupt the hover effect. Testing the current configuration reveals that element B flickers frequently and incorrectly teleports to the top left corner. This issue stems from using offsetX/offsetY instead of pageX/pageY, leading to positioning inconsistencies with respect to zoom levels. Furthermore, maintaining both A and B within the same parent container ('content') is crucial for the hover/show CSS interaction, necessitating element B's placement outside the body tags to align with pageX/pageY behavior.

Query

Are there alternative techniques available to accomplish one or both of my objectives effectively? Is there an unconventional CSS solution for toggling visibility between elements situated in different divisions, or perhaps a JavaScript workaround? Ideally, I wish to avoid jQuery dependencies. My attempts at implementing mouseover and mouseout events were unsuccessful due to erratic triggering causing visual flickering. Additionally, is there a method to calculate the pixel distance between the edge of 'content' and the window's top/left, enabling precise relative positioning adjustments based on pageX/pageY coordinates?

If any unnecessary practices are evident in the given example, or if the observed behavior deviates from the expected output, kindly provide feedback. It is plausible that due to brevity limitations, essential parts of the original code might be omitted here to illustrate the core challenge accurately.

UPDATE

To enhance clarity and accuracy, the actual code utilized in my ongoing project has been shared via this link for reference and review.

UPDATE 2

Clarification: In my specific code (on codepen), element A corresponds to mainitem, while element B corresponds to tooltip-border, as noted by @DavidsaysreinstateMonica in the comments section.

Answer №1

To solve the issue, simply include pointer-events: none; in the CSS for element #B. This will prevent any mouse events from being intercepted by B.

let b = document.getElementById('B');

const onMouseMove = (e) =>{
  b.style.left = e.offsetX + 'px';
  b.style.top = e.offsetY + 'px';
}

document.addEventListener('mousemove', onMouseMove);
* {
 margin: 10px;
}

#content {
  position: absolute; /* Not needed in this example, but required for what I'm trying to make, I'm adding it because it might be relevant. */
  border: 5px solid green;
}

#A {
  border: 5px solid red;
  width: 500px;
  height: 500px;
}

#B {
  display: none;
  position: absolute;
  border: 5px solid blue;
  width: 100px;
  height: 100px;
  pointer-events:none;
}

#A:hover~#B {
  display: block;
}
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="content">
      <div id="A"></div>
      <div id="B"></div>
    </div>
  </body>
  <script src="script.js"></script>
</html>

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

Identifying the pressing of the enter key in an input field

Currently, I am developing an innovative IFrame browser that features an omnibox (identified as "address") and a "GO" button (identified as "submit"). One of the key challenges I'm facing is detecting when the user inputs information and hits the Ente ...

Incorrect way of tallying items in an object and the proper method for tallying similar values between objects and arrays

My attempt was to count the occurrences of the same values in objects and arrays. The goal was to display the initial numbers that appear in arrays within an object. Here is my flawed code along with an example case: let index = {}; let result = []; cons ...

Working with HTML and JSP documents

After completing the front end of my webpage with an HTML file, I now need to fetch data from the server and display it on the webpage. It seems like using JSP is the way to go, but I'm concerned about adding Java code to my already large HTML file, m ...

Bordering the limits with Highcharts

Can I enhance the plot area with a border, similar to the black border shown in the image? https://i.sstatic.net/KirsN.png -- UPDATE -- I am encountering some unwanted white space between the plot area and the border. Is it possible to eliminate this wh ...

Is there a way to modify the express function I created to take in an array as its parameter and reuse it effectively?

I have developed a function that retrieves a JSON object of an Order by finding details based on the Id provided. Below is the code and model for reference. I am looking to enhance this function to also accept an array of ids and return the combined JSON o ...

Ensuring proper alignment of images and text in HTML when resizing

Trying to show an image and text side by side, I'm using the following code: div.out { background-color: silver; border: 1px solid black; padding: 10px; display: flex; } div.right { order: 1; background-color: white; border: 1px soli ...

Creating an HTML table with two arrays displayed and a delete button for confirming deletion

I have created a function to populate two arrays with movie information and display it in a table on the screen. However, I am struggling to make the delete button appear and to separate the titles and directors into different columns. How can I achieve ...

The Bootstrap div is failing to resize proportionately

Although frontend development is not my expertise, I find myself needing to make adjustments to a Bootstrap-based website. I have been tweaking the heights of a specific div that is defined as follows: html: <div class="cover-container d-flex w-100 h- ...

Challenges following the Node 0.10 update

I have been using Node 0.8.25 and Express 3.4.0 successfully. However, when I attempted to upgrade to the stable version of Node 0.10, I encountered some strange issues. One particular route in my application is causing problems after the update: app.po ...

Disabled attribute malfunctioning in AngularJS version 5

Seeking assistance as previous Question and Answer on ng-disabled did not provide a solution, prompting me to ask for help here. In my angularjs app, I am encountering issues with ng-disabled not functioning correctly. To better illustrate the problem, p ...

Navigating between various links using the tab key can result in complications with pseudo-elements when using

When using Chrome, try clicking in the results pane and then hit tab to focus on this first link: http://jsfiddle.net/2q6c7c36/2/ Have you noticed how the contents of .box seem to "jump up" outside of its border? It seems that this issue is related to th ...

Styling HTML Select Box Options

My goal is to display the user's name and email within an option of a select box: <option>Adda <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caabaeaeab8aafb2aba7baa6">[email protected]</a></option& ...

Creating JavaScript code using PHP

In my current project, there is a significant amount of JavaScript involved. I'm finding that simply generating basic strings and enclosing them within "<script>" tags may not be the most efficient approach. What are some alternative methods fo ...

What could be causing mobile phones to overlook my CSS media query?

My CSS includes 3 media queries that function properly when I resize the browser, but fail to work when using the responsive design tool in the inspector ("toggle device mode") and on mobile devices. Snippet of my CSS code : @media screen and (max-width: ...

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

Inheriting the viewBox attribute with SvgIcon

I have a collection of unique custom SVGs, each with its own distinct viewBox. First Custom SVG <svg viewBox="-4 -4 24 24"><path something/></svg> Second Custom SVG <svg viewBox="-5 -7 24 24"><path something ...

Steps for properly closing the loop to input data into an array prior to populating the JSON object in Node.js

I have encountered an issue while trying to fill all the data from my loop into an array. It seems that the loop is being executed last, causing the array to remain empty when I try to print the data. var data = new Array(); for (let station of t ...

Using JavaScript to scan a CSS file and identify any duplicate selectors

Exploring a scenario where I have a string containing CSS selectors, similar to the format below: .u-br { blah blah } .u-tr { blah .blah } .... .u-mr { } The task at hand is to validate the selectors (specifically the .u-tr part) to ensure there ...

"Unlocking the potential of Vue.js: Grabbing the object ID with a

I am encountering an issue with accessing the object ID when I click on the edit or delete buttons in my CRUD operation. The event.target is returning the values of the edit and delete buttons instead. This is what my HTML template looks like: <div ...

interaction with leaflet popup information

My aim is to access the content within a leaflet popup. Specifically, I have inserted a form with buttons inside it that I would like to interact with. However, for now, I am simply attempting to add an event to the popup itself. $(".leaflet-popup-content ...