jQuery tooltip box not functioning correctly

When the mouse enters on li a, the tooltip box (class .show_tooltip) is appearing on the left. I want each tooltip box to display just above or to the left of the link that the mouse is on. The links need to stay on the right as they are now, so please do not modify my html code. Check out the DEMO for an example.

For instance, when hovering over "how", I want the tooltip box to display in a similar manner.

This code is just a small part of my larger code.

CSS:

.show_tooltip{
    background-color: #E5F4FE;
    display: none;
    padding: 5px 10px;
    border: #5A5959 1px solid;
    position: absolute;
    z-index: 9999;
    color: #0C0C0C;
}

HTML:

<ul>
    <li>    
    <div class="show_tooltip">
        Insert returns between paragraphs
    </div>
        <a href="#">about</a>
    </li>

    <li>    
    <div class="show_tooltip">
        Add 2 spaces at the end for a line break
    </div>
        <a href="#">how</a>
    </li>
</ul>

jQuery:

$("li a").mouseenter(function(){
     $(this).prev().fadeIn();
}).mousemove(function(e) {
            $('.tooltip').css('bottom', e.pageY - 10);
            $('.tooltip').css('right', e.pageX + 10);
        }).mouseout(function(){
     $(this).prev().fadeOut();
})

Answer №1

Initially, the markup is becoming quite complex in this scenario. However, since you mentioned not to alter the HTML, here's a solution to position the tooltip next to the link.

See the Demo in Action -> http://jsfiddle.net/bikerabhinav/AQh6y/8/

Explanation: Determine the width of the parent container (to serve as the base)

    var baseWidth = $('ul').outerWidth();

Find the left-offset of the link:

var linkOffset = $(this).offset();

Apply these values to the CSS of the tooltip. Position it absolutely:

$("li a").mouseenter(function(){
    var linkOffset = $(this).offset();
    var baseWidth = $('ul').outerWidth();
$(this).prev().css({right: baseWidth + 20 - linkOffset.left, top: linkOffset.top}).fadeIn();
}).mousemove(function(e) {
        $('.tooltip').css('bottom', e.pageY - 10);
        $('.tooltip').css('right', e.pageX + 10);
     }).mouseout(function(){
     $(this).prev().fadeOut();
});

PS: This method leans more towards being a workaround, but the intention is clear. Ideally, a cleaner HTML structure would be more efficient.

Answer №2

Are you looking to achieve this? --> DEMO

Simply update the position: fixed; within the .show_tooltip{} class.

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

Tips for centering Font Awesome icons in your design:

I'm struggling to align the font awesome icons with a lower text section in the center. Here is the HTML code snippet: .education-title { font-family: Alef, Arial, Helvetica, sans-serif; text-align: center; font-size: 1.5em; } .edu-co ...

Extracting a floating picture from an Excel spreadsheet using ReactJS

Is it possible to extract an image from an Excel sheet that is not contained within a cell, but instead appears to be floating above the cells? The XLSX library only gathers cell information and does not provide a solution. Are there alternative methods su ...

Generated Form Data Automatically

Seeking advice on achieving a specific functionality in ASP.NET Web Form that is similar to the AutocompleteExtender, but requires more flexibility. Here is what I aim to accomplish: There are 2 TextBox fields on the form: CompanyName and CompanyRef (a u ...

Using CSS to create centered blocks

I have a list of blocks that I want to center without any margins, like the example below but margin-free. ul{ margin:0px; padding:0px } .colors{ padding-left: 50px; padding-right: 50px; } .colors li{ display: inline-block; list-st ...

Which method is optimal for organizing tree categories and linking them to posts, as well as locating posts based on a selected category within a MERN stack

Currently, I am utilizing the MERN stack for my project development. The project involves a tree category structure as outlined below: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { type: Boolean }} For ...

Trouble with window.location functionality following an AJAX request

After a successful response from an AJAX request, the window.location method is not working as expected. However, when I debug step by step in Firefox, the window.location works fine. function login(){ var jason ={"usuario":document.getElementById("inp ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

Reserved space for both double and single quotation marks

I've created a function that generates a table of specified size with predetermined content in each cell, and displays it within a designated div ID. generate_table(4, 4, 'Cell Content', 'display') To test this function, I added a ...

Adding fields from one collection to another collection in MongoDB based on specific conditions for a considerable amount of data

I encountered a situation where I constantly need to update a large number of collections. Here are the collections: coll1 { "identification_id" : String, "name" : String, "mobile_number" : Number, "location" : String, "user_properties" : [Mixe ...

How to modify a specific property of an array object in JavaScript

I have an array of objects that looks like this: [ { number: 1, name: "A" }, { number: 2, name: "e", }, { number: 3, name: "EE", } ] I am looking for a way to insert an object into the array at a specific position and ...

Condense everything when displaying one at a time (various divs)

I found the solution at https://getbootstrap.com/docs/4.2/components/collapse/ My query is related to collapsing multiple elements and showing only one when divided into different divs. While it works within the same div, dividing content into separate di ...

Converting a for loop into a fixed-size array?

I am currently developing a backbone application and have been given some sample code by the provider. The code includes a for loop that generates player names as 'player_1', 'player_2', and so on. However, I would like to manually ente ...

Hierarchy of importance when multiple style rules affect an element

When an element in HTML has multiple style rules applying to it, what is the precedence order? The rules that apply to an element identified by its unique id come first Next are the rules applied to all elements of a specific class Lastly are the rules th ...

Having trouble placing the flash element above the HTML?

Despite my efforts to use SWFObject to embed a swf file on my webpage, it seems that the flash movie is covering some of the HTML components. Strangely enough, the HTML elements are bleeding through and appearing on top of the flash content. I've tri ...

The inverse function for Ember Handlebars helper options is experiencing an undefined error

With a template in hand, I needed to toggle the display of certain text based on a method's return value. Research led me to the recommendation of using handlebars helpers for this purpose. So, I implemented a resetPassword helper within the controlle ...

Encountering a situation where attempting to retrieve JSON data results in receiving an undefined

After fetching JSON data from the API , I successfully printed out text to the console with the correct data. However, when attempting to access any of its properties, they are returning as undefined. var url = "http://www.omdbapi.com/?t=batman&y=& ...

Tips for effectively managing Angular JS dependencies and promoting modularity

As I embark on a new project from the ground up, my main focus is creating a responsive website optimized for mobile devices. In order to achieve this goal, I am seeking information about Angular: How does Angular manage its resources and dependencie ...

Callback for remote validation in asp.net core unobtrusive form validation is essential for ensuring data

My login form consists of 2 fields - email and password. The password field is initially hidden, and I require the email to be validated by a remote validator before showing the password field. [Remote("ValidateAccount", "Account", Err ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

Best practice for organizing sort icons in a table with React and MaterialUI

I am currently implementing the following code in a tsx component. I am still learning about the various layout options available. You can view my code on this sandbox link. import React from "react"; import { ArrowDropUp, ArrowDropDown } from "@materia ...