A creative way to display a div upon hovering over a link dynamically

My website has dynamically generated a tags, each with its own corresponding div containing unique content and height. I want to make it so that when a user hovers over an a tag, the matching div is displayed. The div should appear at the position of the mouse cursor and grow upwards from bottom to top, since the links are located at the bottom of the page.

Below is an example of what the code looks like (where $z is a counter):

<a href="<?php echo $link_djv;?>" class="rsshover" id="djvl_<?php echo $z;?>" target="_blank">
    <li>
        <p class="headline"><?php echo $title_djv;?></p>
    </li>
</a>

<div class="preview" id="djvd_<?php echo $z;?>">
    <?php echo $description_djv;?>
</div>

I have searched through various threads but haven't found a suitable solution to this problem yet. Any help would be greatly appreciated. Thank you!

Answer №1

Execute Code

This code provides a basic foundation for your project. While the animation may need refinement, it serves as an effective starting point.

class TooltipManager {
  constructor () {
    this.xCoordinate;
    this.yCoordinate;
    this.links = document.querySelectorAll('a');
    this.addEventListeners();
    this.activeLink = false;
  }
  
  addEventListeners () {
    for (let link of this.links) {
      link.addEventListener('mouseenter', (e) => this.handleMouseEnter(e));
      link.addEventListener('mouseleave', (e) => this.handleMouseLeave(e));
    }
    document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
  }
  
  handleMouseMove (event) {
    this.xCoordinate = event.pageX; 
    this.yCoordinate = event.pageY;
    
    if (this.activeLink) {
      this.activeLink.style.top = `${this.yCoordinate}px`;
      this.activeLink.style.left = `${this.xCoordinate}px`;
    }
  }
  
  handleMouseEnter (event) {
    this.activeLink = event.target.nextElementSibling;
    this.activeLink.style.maxHeight = '50px';
  }
  
  handleMouseLeave (event) {
    let targetContent = event.target.nextElementSibling;
    targetContent.style.maxHeight = 0;
    this.activeLink = false;
  }
  
}

new TooltipManager();
.preview {
  position: absolute;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.6s ease;
}

li {
  list-style: none;
}

a {
  padding: 20px;
  margin: 20px;
  color: white;
  display: block;
  background-color: grey;
  width: 100px;
}
<a href="/" class="rsshover" id="djvl_123" target="_blank">
    <li>
        <p class="headline">some title</p>
    </li>
</a>

<div class="preview" id="djvd_098">
    content 1
</div>
<a href="/" class="rsshover" id="djvl_123" target="_blank">
    <li>
        <p class="headline">some title</p>
    </li>
</a>

<div class="preview" id="djvd_098">
    content 2
</div>
<a href="/" class="rsshover" id="djvl_123" target="_blank">
    <li>
        <p class="headline">some title</p>
    </li>
</a>

<div class="preview" id="djvd_098">
    content 3
</div>

Answer №2

To make your link display a div in the correct location when hovered over, you will need to implement a mouseover event and a corresponding javascript function. You should also include a mouseout event to hide the div once the mouse leaves the link.

One way to approach this is by updating your PHP code as follows:

<a href="<?php echo $link_djv;?>" class="rsshover" onmouseover="showDiv('<?php echo $z;?>');" onmouseout="hideDiv('<?php echo $z;?>');" id="djvl_<?php echo $z;?>" target="_blank">
    <li>
        <p class="headline"><?php echo $title_djv;?></p>
    </li>
</a>

<div class="preview" id="djvd_<?php echo $z;?>" style="display:none;">
    <?php echo $description_djv;?>
</div>

In addition, create a javascript function like this:

    <script>
    function showDiv(counter) {
          document.getElementById('djvd_' + counter).style.display = 'block';
       // Adjust the position of the displayed div here

    }


    function hideDiv(counter) {
         document.getElementById('djvd_' + counter).style.display = 'none';
     }
    </script>

Answer №3

To incorporate CSS into your design, simply nest the div.preview within the a.rsshover.

.rsshover .preview {
            display: none;
        }
        
        .rsshover:hover .preview {
            display: block;
        }
<a href="#" class="rsshover" target="_blank">
    <li>
        <p class="headline">1</p>
    </li>
    <div class="preview">
        ONE
    </div>
</a>
<a href="#" class="rsshover" target="_blank">
    <li>
        <p class="headline">2</p>
    </li>
    <div class="preview">
        TWO
    </div>
</a>
<a href="#" class="rsshover" target="_blank">
    <li>
        <p class="headline">3</p>
    </li>
    <div class="preview">
        THREE
    </div>
</a>

Answer №4

I am not quite sure how you would like the preview to appear, but here is a solution that might be helpful.

(function($) {
  var $currentElement;
  $('.rsshover').on('mouseenter', function(e) {
    $currentElement = $('#djvd_' + $(this).attr('id').substr(5));
    $currentElement.css({
      position: 'absolute',
      display: 'block',
      top: e.clientY + 'px',
      left: e.clientX + 'px'
    });
  }).on('mouseleave', function() {
    $currentElement.hide()
  })
})(jQuery)
.preview {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="rsshover" id="djvl_1" target="_blank">
    <p class="headline">Headline</p>
</a>

<div class="preview" id="djvd_1">
    Description 1
</div>

Additionally, it is advised not to include <li> tags within an anchor tag <a>.

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

How can I refresh the node server during runtime?

In my Express server, I am currently working on defining an endpoint that triggers a restart of the server automatically during runtime. Here is a snippet showcasing how this could be implemented: var express = require('express') var app = expre ...

An elusive melody that plays only when I execute the play command

I am currently working on creating a music Discord bot using the yt-search library, however, I am encountering an issue where it returns undefined when trying to play a song and joins the voice channel without actually playing anything. My approach is to u ...

Personalized Pinterest button to link to a custom URL (Text Link, Image, or Both)

I've been searching for a solution without success. I'm looking to customize the image for my Pinterest (Pin It) button and pin a specific image by URL, not just the current page. Here is the custom link I created: <a href="http://pinterest. ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...

Are you in favor of side-to-side scrolling?

I can't quite recall where I've encountered this concept before, but I do know that there must be a method for creating a horizontal scroll. Imagine you have multiple DIVs in the following structure: <div class="container"> <div> ...

Rendering user actions instantly in React.js without waiting for server propagation

I am currently developing a shopping list web application where users can toggle items as 'checked' or 'unchecked'. The flow of data in this application is as follows: click on item checkbox --> send database update request --> ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

I'm attempting to resize my images to fit within the container, but instead they appear enlarged

I'm struggling to get my images to resize based on the container size, especially when viewed on tablets or phones. The current result is that the images are too zoomed in and I can't figure out what's causing this issue. ...

What is the process for eliminating transparency from the overlay feature while utilizing Dojox/Standby?

Currently, I'm using a spinner image to indicate loading while retrieving data from the backend. However, the spinner widget creates a translucent overlay over the control. Is there a way to disable this translucency so that only the spinner is visibl ...

Is there a way to perfectly center this image with the rest of my text content?

Seeking assistance in aligning this image to the right alongside other text content. Currently, when the code is executed, the image is pushed down and positioned below the text on the right side. Ideally, I would like the image to be aligned evenly with ...

Is it possible to use Ajax to upload images on a website?

I am encountering an issue with uploading images using $.ajax in PHP. The error message I'm getting is: undefined index:files Below are the details of my HTML and JS code: <form id="image_form" enctype="multipart/form-data"> <input t ...

Having difficulty accessing the Material UI Icons

I encountered an issue when attempting to utilize Material UI icons - as soon as I added the icon component, an error occurred. https://i.stack.imgur.com/issmm.png For reference, you can find the code on CodeSandbox at the following link: https://codesand ...

What are the recommended practices for utilizing AJAX effectively?

As I dive into learning javascript best practices, I find myself a bit confused. From what I've gathered, the recommended ajax practice is: function doSomething(arg1, arg2) { jQuery.ajax({ var urlink = resourceURL url: urlink, ...

Alter the background image of a DIV based on the selected menu item

I am working on a project that involves a div element with the class "jumbotron" which currently has a background image applied to it. Additionally, I have a menu consisting of 6 items that I would like to interact with. My goal is to dynamically change ...

Deliver the GWT module in JavaScript format

Currently, I am in need of the following: I need to create a GWT module that can be seamlessly incorporated into a GWT app without requiring recompilation - essentially a plug-and-play solution. This module should include a widget along with various cla ...

Having difficulty transforming a JSON string into a JSON object using Javascript

Currently, I am working on a hybrid mobile application using Angular. I have a string that is obtained from a $http.jsonp request and I am attempting to convert the response into JSON format. After checking the validity of the JSON at , it appears to be va ...

Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles: const colorPickerItem = color => ( <View style={{backgroundColor: color.toLowerC ...

Using Angular.js to update the `ng-model` with the value of text.textContent

There is a javascript event that dynamically updates the value of an input var posx = event.target.querySelector('input.posx'); posx.value = event.dx; This code successfully updates the html: <input type="text" ng-model="posx" si ...