Determine the position of a relative element using jQuery and CSS, then adjust the position of the tooltip

I designed a map that displays different locations, and when you hover over each location, a tooltip appears next to the cursor with information about that specific spot.

The map is used as a background image for the main ul element with an id of "map". Each location is represented by a list item (li), and their positions are set using CSS properties like top and left.

The #map is positioned relatively, while the tooltips are positioned absolutely.

Here's a snippet of the HTML markup:

<ul id="map">
<li><a href="#" class="harewood tip_trigger"><img src="images/marker.gif" width="12" height="12" alt="" /> <span class="tip"><img src="images/thumb.jpg" width="143" height="107" alt="" />Title<br />Click marker for details</span></a></li>

While I can easily show and hide the .tip span using jQuery, my challenge lies in determining the position of the parent .tip_trigger element and then adjusting the tooltip to be 10px away from the cursor.

How would you modify the following jQuery code to achieve this?

$(document).ready(function() {
    //Tooltips
    $(".tip_trigger").hover(function(){

        var pos = $("#map").position();  
        var width = $(".tip").width();

        tip = $(this).find('.tip');
        tip.show(); //Display tooltip
        tip.css({"left": (pos.left + width) + "px","top":pos.top + "px" });

    }, function() {
        tip.hide(); //Hide tooltip
    });
});

I've been experimenting with this concept for some time now, referring to the jQuery documentation, but unfortunately, I haven't been able to crack it yet.

Answer №1

It's a good practice to include an additional step using the each method, as suggested by algiecas.

Here is how you can do it:

$(document).ready(function() {
//Tooltips
$(".tip_trigger").each(function () {
 $(this).hover(function(){

 // Let's assume the image has the class marker
 var pos = $(this).find('marker').position();  

    tip = $(this).find('.tip');
    var width = tip.width();
    tip.show(); //Show tooltip
    tip.css({"left": (pos.left + width) + "px","top":pos.top + "px" });

 }, function() {
    tip.hide(); //Hide tooltip
 });


});
});

Answer №2

For optimal results, it is recommended to utilize the location of the .tip_trigger element rather than the entire #map

var position = $(this).position(); 

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

Replacing an Angular 2 application with a new webpage

I've been working on a project using Angular 2 and following this tutorial: Every time I run my api with npm run api on localhost:3000, the entire application gets replaced by another webpage. https://i.sstatic.net/5pIfX.png Here is my package.json ...

A method to transfer a floating point number from Python to JavaScript without using cgi

Running an Apache server from a Raspberry Pi, I have a Python script that prints sensor input to the console. A PHP script then processes this output and controls a light based on the sensor reading before printing it again. Everything works fine when exec ...

Test success despite Cypress assertion failing

Conducting integration tests on an API. Encountering a scenario where one test passes while another fails despite having similar assertions. Feeling confused about the handling of async/promises in cypress. context("Login", () => { // This t ...

Transferring information via a function to a modal component in VueJS

Seeking advice on passing data to a modal. I'm attempting to pass data to a modal, where a function within a v-for loop gathers the video URL for later opening. The modal is placed outside the v-for loop to prevent all videos from playing the same o ...

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

JavaScript button for displaying and hiding all content in one click

I came across a tutorial on W3Schools that showed how to create collapsibles, and I thought it would be great to have buttons that could expand or collapse all at once. I've been trying to implement this feature using the code provided in the tutorial ...

Change the color of the menu icon based on the specified HTML class or attribute

I'm trying to create a fixed menu that changes color depending on the background of different sections. Currently, I am using a data-color attribute but I am struggling with removing and adding the class to #open-button. Adding the class works fine, ...

Ways to modify the gap between buttons using CSS

I am faced with a design challenge on my home page. I want to add some spacing between the buttons so they are not too close to each other, but for some reason margin-top and margin-bottom properties are not working as expected. Can you help me figure out ...

The Angular menu items that have dropdowns attached are not showing up on the screen at all

I have been working on developing a complex Angular menu, and while I have made progress with the overall structure, I am stuck on a particular issue. The menu needs to display different options based on the user's role, such as "admin." However, desp ...

How can I access a PHP variable from an external .php file within a JavaScript script?

I have recently implemented a JavaScript code called "upload.js" for uploading files to my server: function beginUpload(){ document.getElementById('upload_form').style.visibility = 'hidden'; return true; } function endUpload(s ...

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

How can a CSS class be used to toggle the visibility of a DIV element with JavaScript?

I've been researching and came across several scripts that allow for toggling the contents of a DIV by clicking on a button, however, they all use IDs. What I am looking to achieve is similar but using classes instead of IDs. This way, if I want to h ...

The event handler is not being triggered when selecting the tag

Currently working on a project where I am utilizing vanilla HTML/CSS/JS. My goal is to hide all items on a page initially, set a default option in a select tag, display only the element with the selected ID, and allow the user to choose different time peri ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...

The AJAX .load() function will fail to retrieve any content

Currently delving into the world of JQuery/AJAX and experimenting with a simple 'load' function. Strangely, when I trigger the function on an element within my HTML code, it appears unresponsive. No error messages are being generated, leaving me ...

What steps should be taken to complete orders following the checkout.session.completed event triggered by Stripe?

Having an issue with Stripe's metadata object that has a limit of 500 characters. My checkout flow is operational, but the only constraint is the character limit for my cart. I need to include extras and customer notes in my cartItems object for each ...

Tips for preventing chunk loading in webpack: [Angular] [inline js]

Currently, I am working on bundling an Angular project into a single file that includes JS, CSS, and HTML. So far, I've successfully integrated the HTML and CSS, and have made the JS inline using HtmlWebpackInlineSourcePlugin. The minified JS files ge ...

"Triggering an AJAX POST request with a click event, unexpectedly receiving a GET response for

Hello there! I am currently attempting to send an AJAX POST request when a button is clicked. Below is the form and button that I am referring to: <form class="form-horizontal" > <fieldset> <!-- Form Name --> <legend> ...

What is the best way to incorporate a state parameter into a URL when making a GET request with Axios in ReactJS?

Currently, I am utilizing the axios library within a React application to fetch data from a Django backend. I have successfully retrieved user data and stored it in the component's state. However, I now require one of the attributes from the user_data ...

Arranging object arrays according to strings

Imagine there is an array: var a = [ { name: 'Tom', surname: 'TestAsIvanov' }, { name: 'Kate', surname: 'Ivanova' }, { name: 'John', surname: 'Alivanov' }, { name: 'Ivan&apos ...