Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link.

The issue at hand is that the newly created div does not appear in the desired location, but rather ends up being displayed at the bottom. I'm looking for a way to have the new div show up right next to the element that is being hovered over. Is there a solution to achieve this?

$(".bubble").live({
    mouseenter : function() {
        $("#bubble").show();
        $("#bubble").html($(this).attr('id'));
    },
    mouseleave : function() {
        $("#bubble").empty();
    }
});
#bubble{
    width:100px;
    height:20px;
    background-color:#666666;
    position:absolute;
    display:hidden;
}
<ul>
    <li><span class="bubble" id="test1">test1</span></li>
    <li><span class="bubble" id="test2">test2</span></li>
    <li><span class="bubble" id="test3">test3</span></li>
    <li><span class="bubble" id="test4">test4</span></li>
    <li><span class="bubble" id="test5">test5</span></li>
</ul>
<div id="bubble"></div>

Answer №1

To properly position the #bubble in relation to the li element being hovered over, you can try the following code:

$("ul").on('hover', '.bubble', function(e) {
    if (e.type == 'mouseenter') {
        var $el = $(this);
        $("#bubble")
            .html($el.attr('id'))
            .css({
                top: $el.offset().top,
                left: $el.offset().left + $el.width()
            })
            .show();
    }
    else {
        $("#bubble").empty();
    }
});

Here's an example fiddle to demonstrate this

Please note that I have replaced the deprecated live() method with on() using a delegate, and utilized the hover event in the updated code.

Answer №2

How can we achieve this using only CSS?

HTML:

<ul>
<li>
    <span class="bubble" id="test1">test1</span>
    <div>test1</div>
</li>
<li>
    <span class="bubble" id="test2">test2</span>
    <div>test2</div>
</li>
<li>
    <span class="bubble" id="test3">test3</span>
    <div>test3</div>
</li>
<li>
    <span class="bubble" id="test4">test4</span>
    <div>test4</div>
</li>
<li>
    <span class="bubble" id="test5">test5</span>
    <div>test5</div>
</li>
</ul>

CSS:

ul li div {
    width: 100px;
    height: 10px;
    background-color: #666666;
    position: absolute;  
    display: none;
}

ul li:hover div {
    display: inline;   
}

JSFiddle: http://jsfiddle.net/H2ZMc/

Answer №3

Here is a helpful solution:

Check out the JS-Fiddle Demo here

I added the #bubble to the li element

$(".bubble").live({
           mouseenter : function() {
               $("#bubble").html($(this).attr('id'));
               $(this).append($("#bubble").show());               
            },
            mouseleave : function() {
             $("#bubble").empty().hide();

            }
  });

Answer №4

Give this a shot:

let bubble = $("#bubble");

$(".bubble").on({
    mouseenter : function(e) {    
        $("#bubble").html($(this).attr('id'));
        e.target.appendChild(bubble);
    },

    mouseleave : function() {
        $("#bubble").empty();        
    }
});

This code snippet appends the bubble element to the element where the mouse is over. To adjust its position, consider adding display: inline to the div so it appears next to other sibling elements instead of below them.

Answer №5

Follow Mica's advice and be sure to exclude the position:absolute; attribute as well.

Thus, your revised CSS code should look like this:

#bubble{
width:100px;
height:10px; 
background-color:#666666;
display:hidden;
display: inline;
float: left;
}

ul{
display: inline;
float: left;   
}

http://jsfiddle.net/abc123/45/

Answer №6

Is there a reason to utilize .on() even when the presence of the #bubble element is already established?

$(".bubble").hover( function( ) {

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

    $("#bubble").html($(this).attr("id"))
        .css({ top: offset.top, left: offset.left + $(this).width() })
        .show();
}, function( ) {
    $("#bubble").html("").hide();
});

Check out the live example on this link

Answer №7

By applying the specified styles to both the <ul> and the <div>, it should function correctly.

display: inline;
float: left;

Answer №8

$(".bubble").on({
    mouseenter: function() {
        $("#bubble").show();
        $("#bubble").html($(this).attr('id'));

        var position = $(this).position();
        $("#bubble").css({left: position.left + $(this).outerWidth(), top: position.top });
    },
    mouseleave: function() {
        $("#bubble").empty().css({top: '', left: ''});
    }
});​

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 making a scrollable container that allows its contents to overflow without clipping?

Currently working on implementing a horizontal card row for my website with a unique hover effect - the cards lightly rotate and raise on hover. Here is a preview: https://i.sstatic.net/eDQ59.gif To make this row responsive, I added overflow-x: auto; to e ...

Conceal elements when they are too small without the use of JavaScript

I want to be able to hide content when the window size is below a certain point. After finding an example at (http://css-tricks.com/dynamic-page-replacing-content/), I still couldn't figure out why it actually works. <div class="container"> ...

Disable the movement and dragging functionality of the scroll feature in Google Maps using React

I have a map.jsx file in my React application that contains the code below: import React from 'react'; import GoogleMapReact from 'google-map-react'; import './map.css'; const Map = ({ location, zoomLevel }) => ( <d ...

Interacting with jQuery through JSON requests and decoding them in PHP

I've spent hours scouring through various online resources like StackOverflow and Google in search of a solution to get my ajax functionality working. My goal is to send data using json to a php form, then decode the json in php, process it, and final ...

Making an asynchronous request using Ajax to verify the status of a checkbox

I have two checkboxes, and I want to make an ajax call to a jsp page when one of the checkboxes is clicked. The jsp page should display a table with data fetched from a database. The issue arises when dealing with two checkboxes: <div class="search-in ...

Is there a way to retrieve the id attribute of an option element from the source component?

When a user makes a selection, I am trying to access the id attribute of the HTMLOptionElement. However, it always returns 0 instead of the actual id I passed (such as 1 or 2) from the select tag: <div class="col-8"> <select (cha ...

Issues with the CSS code causing the dropdown menu to malfunction

Having trouble getting my CSS to apply when creating a drop-down menu. I've set up UL and LI elements for the dropdown, but the styling is not rendering as expected. Check out the screenshot below for a look at how it currently appears using developer ...

IE8 experiencing issues with displaying Recaptcha AJAX API widget

Struggling with getting the Recaptcha widget to show up in IE 8, even though it works fine in Firefox, Safari, and Chrome. I've set up a feedback form that loads via AJAX when a user clicks a link, and I'm using the Ajax API directly to place th ...

Finding the location of an "Apply" button on an Angular HTML page

There is an issue with the positioning of the apply button in the filter bar. Sometimes it displays in the next row instead of alongside the other filters. How can I determine the exact position of this apply button within the HTML page? <div class=&quo ...

Modify HTML content according to the response received from the backend

I am trying to dynamically update the text content of an HTML tag based on a response from the backend. My application is running on a Django server where I have a timer in the backend measuring the processing time. I need to send this processing time to t ...

Struggling to locate a straightforward sidebar solution without relying on Bootstrap. Finding an easy-to-use answer seems

I have a lightweight and easy-to-understand code for a website project with two panels. The first panel on the left is a large navigation (270px width, top to bottom, similar to a wiki) with approximately 30 unordered list items. Next to it is the second ...

Exclude the node_modules directory when searching for files using a global file pattern

I'm facing some challenges setting up a karma configuration file because I am having difficulty creating a glob that correctly matches my files. Within my lerna repository, there may be node_modules folders inside the packages, and it's importan ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...

Bringing in a variable from a React component to a JavaScript file

I've created a React component called Button with two states named name and players. Now, I need to access these states in a separate JavaScript file that is not a component. Below are the relevant code snippets: Button.js import {useState} from &qu ...

Tips for Creating a Fixed-Width Element

I am struggling with creating text wrapping around a box inside a full width page template on Wordpress. The plugin developer suggested wrapping the text inside a fixed width element, but I am unsure how to do this. Any assistance would be greatly apprecia ...

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

Transferring parameters from a jQuery post function to a controller

I am facing an issue where the controller is not receiving the "name" parameter that I want to send as a parameter. $(document).ready(function () { $("#btn1").click(function () { var name = $("#search").val(); //name = "ali"; alert(name); ...

Rearrange and place items at the dropped location

I am looking to create a drag-and-drop feature for moving items from a list of products to an empty container. Upon completion, I need to save the location and the selected items in a database so that I can recall this layout later. However, I have encoun ...

How can I set a default radio button selection when the page is loaded?

Input your radio button code below: <ion-radio ng-model="data.gender" ng-required="true" ng-value="'male'">Male</ion-radio> <ion-radio ng-model="data.gender" ng-required="true" ng-value="'female'">Female</ion-rad ...