Steps to show a tooltip next to each image

I've been working on implementing a jQuery tooltip effect on several images, and it seems to be functioning properly. However, I'm facing an issue where the tooltip only displays at the top of the page regardless of which image is clicked. Is there a way to adjust the code so that the tooltip appears next to each image upon clicking?

Below is the current jQuery code I have:

$('.image').hover(function () {
    $('.tooltip').fadeIn(1000);
}, function () {
    $('.tooltip').fadeOut(1000);
});

$('.tooltip').css({
   top: e.pageY,
   left: e.pageX
})

CSS

.tooltip {
    display: none;
    height: auto;
    position: absolute;
    background-color: #D1C585;
    color: black;
    border: 2px solid rgba(128, 0, 32, 0.3);
    padding: 5px;
    border-radius: 5px;
    font-family: actor;
}

HTML

<img src="image.jpg" class="image">

Answer №1

To ensure proper positioning, the element should have the CSS property position: absolute, with its containing parent set to position: relative. Within the hover action, include the following code:

$('.tooltip').css({
  top: e.pageY,
  left: e.pageX
})

Answer №2

Depending on the location of the tooltip node, you can determine the fixed position of the image by calculating the offsetLeft/offsetTop of the element and its parents. Here is an example:

$('.image').hover(function() {
    var e = this,top=0,left=0;
    while(e){
        top+=e.offsetTop;
        left+=e.offsetLeft;
        e=$(e).parent();
    }
    $(this).css({position:'fixed',top:top+"px",left:left:left+"px"});
    $('.tooltip').fadeIn(1000);
}, function() {
    $('.tooltip').fadeOut(1000);
});

I have not tested this code, but it should guide you in the right direction. You can then utilize the size of the image (offsetHeight and offsetWidth) to properly position the tooltip around the image.

Answer №3

Check out this sample showcasing the utilization of jQuery UI, refer to jQuery UI tooltip for additional details.

HTML

<img src="http://img262.imageshack.us/img262/68/sahara4rs.jpg" title="tyre">

Javascript

$(document).tooltip({
    track: true,
    show: {
        effect: "fade",
        delay: 1000
    },
    hide: {
        effect: "explode",
        delay: 250
    }
});

View it on JSFiddle

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

Secure an input field for exclusive attention. React

How can I lock the focus of my input field? I attempted using the following code: onBlur={this.click()} However, it was not successful. What is the correct way to accomplish this? ...

creation of objects using constructors in Node.js

As I delve into the world of Node.js, a burning question has arisen - how can I make a function accept multiple strings in the form of an array? Picture this scenario: export default (config: Config) => { return { target: 'https://google.com ...

Optimal approach for organizing a mysql+nodejs+express application

In my development process, I typically utilize mysql without sequelize. To establish the database connection, I usually create a module.export function that can be required in other files. Here's an example: var db; module.exports={ getConnection = f ...

Establishing parameters in a Socket.io chatroom

I am encountering an issue when attempting to store information in the socket room variables. The error message I receive is: UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'host' of undefined This is the snippet of my code: io ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

When implementing the Parse Client Key in an Angular application, it may lead to encountering

I have been working on retrieving a class from Parse using a client key with the GET method. Successfully sent a request through Advanced Rest Client for Google Chrome by including X-Parse-Application-Id and X-Parse-Client-Key headers. [edit] [edit2] Resp ...

I am unable to retrieve data from my Firestore database using Geofirestore within an Express application

I implemented a query in Express to retrieve my data. Below is the code for my Express function: app.get('/locatii', (req, res) => { const geofirestore = new GeoFirestore(db); const geocollection = geofirestore.collection('locati ...

I am interested in implementing a logout feature using a button in PHP

<?php session_start(); ?> <form> <input type="button" id="logout" value="logout" name="logout"> </form> After initializing the session during login, I am seeking to terminate it using a button rather than via <a href="">l ...

Enhancing image search functionality through dynamic HTML updates

I need help figuring out how to update the link address for profile pictures on my NHL stats website. Currently, I am using a script to append the image to the body, but I don't know how to properly add the player ID ({{p1_ID}}) to the link and includ ...

Ways to detect when the user begins typing?

There is an input box with a cross icon that clears the input when clicked. The icon is visible even when the box is empty, which may not make sense. It would be better to show the icon only when the user starts typing. How can I detect when the user start ...

Get the value of a function that was previously assigned to an onclick event using JavaScript

Here is the code snippet I am currently working with: document.getElementById(myid).onclick = function() { HandleGPIO(val1, val2); }; if (console) { console.log(document.getElementById(myid).getAttribute('onclick')); } My goal is to de ...

Preserve Text Selection While Utilizing DIV as a Button

I wonder if this issue is specific to the browser I'm using? Currently, I'm using Chrome... My goal is to enable users to save any text they've highlighted on the page with their cursor. I've set up the javascript/jQuery/ajax and it w ...

Success Message Appearing on Contact Form Page

Seeking guidance on integrating PHP with Ajax to send emails. While I have basic knowledge of the mailer, my understanding of Ajax is limited. After skimming through a book, I attempted to write code using both technologies. Could someone please review my ...

Flexbox causing spacing problems in HTML/CSS navigation bar

I have encountered a unique issue that I cannot seem to find a solution for, so here goes: I am in the process of designing a navigation bar with the heading positioned on the left-hand side and the navigation items on the right. My goal is to center the ...

Utilize React-markdown to interpret subscript text in markdown format

I tried to create subscript text in an .md file using the following syntax: x_i x~i~ Unfortunately, react-markdown did not interpret this as subscript. After some research, I discovered the package remark-sub-super and implemented it with the plugin ...

Utilize JavaScript to restrict interactions to touch events in HTML

I am using JavaScript to create an HTML5 game where players can buy items using buttons. Unfortunately, I am unable to use ontouchstart='function()' for my buttons. Instead, I am utilizing the touchstart event listener and waiting for users to ta ...

Data from the table will be utilized in an SQL query according to a particular table row

My PHP script is set up to query my database and pull data based on the value of the acceptance field. SELECT * from database WHERE acceptance = 1 This process is working smoothly. Following that, my PHP script loops through the retrieved object to popul ...

When using Lodash, it will successfully operate on two objects but will yield a null value if presented

Check out this interesting plunker I have here... I've noticed that when the 3rd item is deleted from the original, the calculation for total_expenses comes out as 23196. However, when the third object is included, total_expenses returns null. Is the ...

Is there a way to transform my drag-and-drop function into a click event instead?

I am currently contemplating a modification to my drag and drop game. The game involves a grid of words, with the highlighted word to be spelled. Traditionally, players would drag and drop letters to complete the word. However, I am now exploring the idea ...

Utilizing Jquery's replaceWith method to selectively target a particular division

My HTML document includes multiple DIV elements: <div id="div1"></div> <div id="div2"></div> When using jQuery in my script, I attempted to use the replaceWith method to replace a specific <div> with <div>I'm new ...