Creating a tooltip for new list items: A step-by-step guide

I'm currently working on creating a tooltip using JQuery for incoming list items. Users will input text in a textfield, press enter, and those values will be displayed in a visible list on the website. I intend to have a tooltip associated with each item added to the list that displays the text entered by the users. Is it possible to achieve this? If so, how can I implement it? Thank you! This is my progress so far..

<div id="tooltip"></div>

<input type="text" id="input" placeholder="Enter item" /> <button id="button">Add</button>

<ul id="grocery-list">


  </ul>

        ----------------------------------------------------------------------------




 $(document).ready(function(e) {

      $('#button').on('click', function (){

      var addItem = $('#input').val();
      var removeItem = '<a href="#" class="remove">Remove</a>'


      <!--add list item-->

      $('#grocery-list').prepend('<li>' + addItem + '' + '\t' + removeItem + '</li>');

    });


    <!--remove list item-->


    $('#grocery-list').on('click', '.remove', function(){

      $(this).parent('li').remove();

    });

    <!-textfield empty-->


    $('#input').on('click', function (){

      $(this).val('')

    });


    $('#grocery-list').hover(

    function (){

      $('#tooltip').css('display', 'block')
    },

    function (){

      $('#tooltip').css('display', 'none')
    };

    );


    }) ;

    ----------------------------------------------------------------

    #tooltip {

      position: absolute;
      top: 100px;
      right: 300px;
      border: 1px solid #000000;
      border-radius: 5px;
      color: black;
      width: 100px;
      display: none;

    }

The tooltip is visible, but I would like the text entered in the textfield to be shown in the tooltip. Feel free to reach out if you require more information. Thank you in advance (verwijderen = remove, toevoegen = add)

Answer №1

There are a couple of key adjustments that need to be implemented:

  1. You must save the toevoegen data along with the li in an organized manner.
  2. The hover event should be attached to the li element, not the ul. Specifically, this should apply to any future li elements added to the ul.

For the first point, utilize jQuery's data() function to store the tooltip value:

var li = $('<li>' + toevoegen + '' + '\t' + verwijderen + '</li>');
li.data('tooltip', toevoegen);
$('#boodschappenlijst').prepend(li);

For the second adjustment, you need to employ on() instead of hover() to ensure proper attachment of the event to new li items:

$('#boodschappenlijst').on('mouseenter', 'li', function () {
    var toevoegen = $(this).data('tooltip');
    $('#tooltip').css('display', 'block').html(toevoegen);
}).on('mouseleave', 'li', function () {
    $('#tooltip').css('display', 'none').html('');
});

Here is the cleaned-up version for your reference:

$(document).ready(function (e) {

    $('#button').on('click', function () {
        var toevoegen = $('#input').val();
        var verwijderen = '<a href="#" class="verwijderen">Verwijderen</a>';
        //add list item
        var li = $('<li>' + toevoegen + '' + '\t' + verwijderen + '</li>');
        li.data('tooltip', toevoegen);
        $('#boodschappenlijst').prepend(li);
    });

    // remove list item
    $('#boodschappenlijst').on('click', '.verwijderen', function () {
        $(this).parent('li').remove();
    });

    // textfield empty
    $('#input').on('click', function () {
        $(this).val('');
    });

    $('#boodschappenlijst').on('mouseenter', 'li', function () {
        var toevoegen = $(this).data('tooltip');
        $('#tooltip').css('display', 'block').html(toevoegen);
    }).on('mouseleave', 'li', function () {
        $('#tooltip').css('display', 'none').html('');
    });
});
#tooltip{
     position: absolute;
     top: 100px;
     right: 300px;
     border: 1px solid #000000;
     border-radius: 5px;
     color: black;
     width: 100px;
     display: none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="tooltip"></div>

<input type="text" id="input" placeholder="Enter item" /> <button id="button">Add</button>

<ul id="boodschappenlijst"></ul>

Answer №2

UPDATE: Here is the latest answer.

View the working example

$(document).ready(function(e) {

var myToolTip = $('#tooltip');

  $('#button').on('click', function (){

  var newItem = $('#input').val();
  var removeItem = '<a href="#" class="remove">Remove</a>'

  $('#shoppingList').prepend('<li class=\'hoverTarget\' title=\''+newItem+' \'>' + newItem + '' + '\t' + removeItem + '</li>');

      $('.hoverTarget').hover(

          function (_evt){

          console.log("e",_evt);

          console.log("e",_evt.currentTarget.attributes['title']);

           myToolTip.html(_evt.currentTarget.attributes['title'].value);      

           myToolTip.css('display', 'block')
},

function (){

  myToolTip.css('display', 'none')
}

);

});

$('#shoppingList').on('click', '.remove', function(){

  $(this).parent('li').remove();

});


$('#input').on('click', function (){

  $(this).val('')

});





}) ;

Make sure to include a title attribute for each list item

 $('#shoppingList').prepend('<li title=\''+newItem+'\'>' + newItem + '' + '\t' + removeItem + '</li>');

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

Angular CodeMirror Line-Break function not displaying line numbers

I am currently utilizing Code Mirror from ngx-codemirror. My goal is to split the line when it fits within the width of the parent container. After searching, I found a couple of solutions that suggest using: lineWrapping: true Additionally, in the styles ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

What is the proper method to trigger a re-render of a React functional component with the useEffect

Within my top-level component, I am utilizing a library to determine if a user’s browser is in light or dark mode. This information is then used to set the theme for the application, which includes HTML Canvas elements (it's crucial to note that the ...

Using jQuery to strip inline styling from copied webpage content

When I copy content/paragraph from Wikipedia and try to paste it as code on my webpage dynamically, it ends up with a lot of inline styles. I want the code to be clean and properly formatted in HTML. I have tried several methods, but they remove all the ta ...

The Best Way to Refresh a ReactJS Component in Plain HTML/JavaScript

So here's the situation. I'm diving into creating a React Modal component that can seamlessly integrate with any vanilla HTML / JS file. By generating a bundle.js file using Webpack from my React component, it becomes easier to inject it into a d ...

Need two clicks for React setState() to update the user interface

As someone who is new to React, I've come across a common issue that many developers face. Despite trying various solutions, I still find myself having to click twice to update the UI state. The first click triggers the event handler but does not upda ...

Tips for integrating Laravel's blade syntax with Vuejs

Can you guide me on integrating the following Laravel syntax into a Vue.js component? @if(!Auth::guest()) @if(Auth::user()->id === $post->user->id) <a href=#>edit</a> @endif @endif ...

Do we need to include href in the anchor tag?

Why am I unable to display the icon within the <anchor> element without using the href attribute? The icon only appears when I set the href attribute to "". Even if I manage to show the icon by adding href="", adjusting the size with width and height ...

Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not ...

The method for connecting the width of a panel to the height of the viewport in Ext Js

I'm looking to automate the adjustment of a panel's height based on the viewport's height using Ext js. Although achievable using listeners, I believe utilizing Ext js variable binding would be more efficient. However, I've encountered ...

Display or conceal a <div> segment based on the drop down selection made

A dropdown menu controls the visibility of certain div elements based on the selection made. While this functionality is working for one dropdown, it's not working for another even though the code is very similar. I've tried various solutions but ...

What is the best way to transform a JavaScript object into a JavaScript literal?

Currently, in my nodejs project, I have an object defined as follows: const objA = { key : 'value' }; My goal is to create a new file named obja.js which should contain the same literals from the object, rather than as a JSON literal. How can I ...

Chart: Observing the Discrepancy in the Initial X-Axis Points

I'm working on incorporating multiple charts onto one page, with each chart centered and stacked one after the other. I've set a fixed width for the graph canvas. The challenge arises from the varying ranges of tick values - one chart may have a ...

Utilize Bootstrap modal to input information into the DataTables library

I am trying to use a bootstrap modal to insert data, but I am encountering an error on the action index. As a result, the button that I added is not functioning correctly. Can someone please review my code to see if there are any mistakes? User Action Con ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

https://i.sstatic.net/7CzRg.png Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically intere ...

Performing a Javascript ajax post of a canvas snapshot in "image/jpeg" format to an asp.net web form

Here is the JavaScript AJAX code snippet: var dataURL = canvas.toDataURL("image/jpeg"); var xhr = new XMLHttpRequest(); xhr.open("POST", "myPage.aspx", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechan ...

Develop a cutting-edge front end for Hyperledger Fabric 2.2 with React js and enhance it with a node

Currently, I have developed a unique hyperledger fabric 2.2 blockchain network using javascript and am looking to integrate it with a React.js front end utilizing the node.js API. Despite my efforts to find relevant examples, most resources focus on hyperl ...

What are some ways to incorporate texture into objects using three.js?

Having trouble adding texture to my central sphere (earth) without the object disappearing. Can someone provide guidance on where I might be making a mistake? Your help is appreciated. For reference, here is the link to my jsbin http://jsbin.com/cabape/edi ...

What is the best method for securing my API key within the script.js file while utilizing dotenv?

My goal is to conceal my API key using dotenv. Interestingly, when I replace require('dotenv').config(); with my actual API key in the code as apiKey: process.env.API_KEY, it works fine despite not using process.env.API_KEY. I made sure to inst ...

Leveraging ng-switch for template swapping

I'm currently facing an issue in my Angular app where I want to switch from a "sign in" form to a "sign up" form when the user clicks on the "Sign Up" button, but nothing happens upon clicking the button. The sign-in form persists on the screen withou ...