There seems to be an issue with the on() function in jQuery when using mouseover

I am trying to implement a small popup box that appears when I hover over some text, but for some reason it's not working as expected. Can someone please help me troubleshoot this issue? My goal is to display the content from the "data-popup" attribute when hovering over the word "surpi". The HTML line containing this dynamic content is generated using JavaScript. Here is the code snippet:

<a href="#" data-popup="surpris">supri</a>
$(document).ready(function() {
  popup();
});

function popup() {
  $("#correction").on("mouseover", "a", function() {
    var data = $(this).attr("data-popup"),
      offsetDataTop = $(this).offset().top,
      offsetDataLeft = $(this).offset().left;

    if (data != "") {
      // Create .popup element
      $("body").prepend("<div class='popup'>" + data + "</div>");
      // Set properties for .popup
      var popupWidth = $(".popup").innerWidth(),
        thisWith = $(this).innerWidth(),
        marginLeft = (thisWith - popupWidth) / 2;
      // Initialize .popup
      $(".popup").css({
        opacity: 0,
        top: offsetDataTop - 40,
        left: offsetDataLeft + marginLeft
      });
      // Animate .popup
      $(".popup").animate({
        opacity: 1,
        marginTop: 20
      }, "fast");
    }
  }, function() {
    $(".popup").remove();
  }); // Remove .popup
};

Answer №1

Here is my approach using mouseenter and mouseleave:

$(document).ready(function() {
  $('#solution').on('mouseenter', '[data-tooltip]', function() {
    var $this=$(this)
    var data =$this.attr("data-tooltip").trim();
    var offsetDataTop = $this.offset().top;
    var offsetDataLeft = $this.offset().left;
    if (data != "") {
      // Create tooltip
      var $tooltip=$("<div class='tooltip'>" + data + "</div>");
      $("body").prepend($tooltip);
      
      // Set tooltip properties
      var marginLeft = ($this.innerWidth() - $tooltip.innerWidth()) / 2;
      
      // Initialize tooltip
      $tooltip.css({
        opacity: 0,
        top: offsetDataTop - 40,
        left: offsetDataLeft + marginLeft
      }).animate({
        opacity: 1,
        marginTop: 20
      }, "fast");
    }
  }).on('mouseleave', '[data-tooltip]', function() {
      $(".tooltip").remove();
  })
});
.tooltip{
  position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="solution">
<br>
<br>
  <a href="#" data-tooltip="amazing">awesome</a>
</div>

<div id="output"></div>

Answer №2

Modify this section:

$("#correction").on("mouseover", "a", function() {

With this:

$("#correction").on("mouseenter", "a", function() {

Answer №3

1) The element you are targeting with #correction does not exist in your provided example. You must add this id to the element

<a href="#" id="correction" data-popup="surpris">supri</a> 

2) Instead of executing the popup method as shown in your code, you can directly bind to the element like this:

$("#correction").on("mouseover", function() {
    // Perform actions here
});

3) To remove the popup element using the mouseleave event, you can combine both functions within the same method:

$("#correction").on({
    mouseover: function () {
        // Perform actions here
    },
    mouseleave: function () {
        // Perform actions here
    }
})

Check out https://jsfiddle.net/mark_c/jtwnyeLy/ for a demonstration.

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

Using Kendo Grid to Transfer Data Between Grid Cells

Recently, I encountered a problem in my Kendo MVC project where I needed to drag a product code from one Kendo Grid to another when the cell value was empty. Here's the scenario: Grid A contains products ordered, but the vendor sending the list has i ...

Pass the html form data to a PHP variable

I need assistance with updating a PHP variable with the value of an HTML form submission. Here is the code snippet: <form action="callback2.php" method="POST"> Enter Phone Number: <input type="text" size="10" name="nummerb" id="nummerb"> <i ...

Rearrange list items by dragging and dropping

Here is the HTML and TypeScript code I have implemented for dragging and dropping list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop List in Green Area: </h4> <ul class="unstyle"> <l ...

How can we refine the user information based on the selection of a radio button?

How do I apply a filter to user details when selecting a radio button? Visit Plunker *I need to display only the questions of authenticated users on the list page, so I created a plunker example. If the user is authenticated or an admin, I want to filter ...

Adjust the header and menu color as you scroll

Starting fresh with JavaScript, I'm seeking advice on a specific piece of code. Working on a Joomla 3.2 website using the Gantry template by default. My goal is to achieve the following: When a user accesses a submenu (e.g., 01, 02, 03) derived from t ...

Having difficulty locating the identification number of an item within the HTML coding

I'm currently trying to locate the ID of the "proceed to checkout" button for a bot that I am developing for my mother on the Best Buy website. However, it seems like the button's ID is hidden and I'm unable to determine how to uncover it. A ...

Adding an information panel to each column in jqgrid allows the grid to display a scrolling feature

We have implemented a jQuery grid where the last column contains a link. When this link is clicked, a new panel should appear providing additional information. To achieve this, we utilized a formatter that generates a hidden div along with the link. Howev ...

Can you modify a specific column in a table using mat-table in Angular material?

For my project, I am utilizing Angular Material's table to present data in a tabular format. However, due to a new requirement, I now need to enable in-line editing for the last 2 columns alongside highlighting another column when the user clicks on t ...

Adjust the CSS property dynamically based on the quantity of items within a div container

Can CSS3 be used to style the children divs of a parent div with specific conditions, such as: If there are 3 divs, apply property x to divs 1 and 2. If there are 2 divs, apply property x to div 1. If there is 1 div, do not apply property x to it. Is jQ ...

Chrome is where all the action happens, while Firefox prefers to keep things on the left

After a long break, I returned to designing my website and re-learning CSS. My approach involved creating a WordPress-integrated site with minimal HTML/PHP work, focusing more on utilizing the available CSS classes and IDs provided by a template theme (Bla ...

Looking for a reliable contact form?

I am currently in the process of developing an email contact form for a client's website. During my research, I discovered methods to enhance the security of contact forms which piqued my interest. 1. Are there significant risks associated with not ...

Dynamic Bootstrap Popover: Creating interactive popups by dynamically attaching events to buttons

I am looking to implement the Bootstrap Popover module to create a confirmation dialog for a delete action. When a <button> is clicked, instead of immediately executing a function, I want a popup to appear allowing the user to either confirm or dismi ...

Troubleshooting script not detecting changes in form

I am currently implementing a script to detect any changes in the form fields and notify the user if there are any. However, instead of triggering the alert box as intended, a different JavaScript box is displayed. Despite my efforts, the script is not re ...

How can I populate a select dropdown list in Django using JsonResponse?

I've been working on displaying a list from my Django application in an HTML select option, but I'm having trouble getting it to show up. Also, I believe I need to assign IDs to the option values in the select list, but I'm not sure where to ...

Sometimes the data-autoplay feature does not function properly in jQueryfullPage.js

I am in the process of developing an HTML page using jQueryfullPage.js. Within this page, I have incorporated 17 videos across 17 different sections. These videos are presented as YouTube iframes with a data-autoplay attribute. Overall, everything is fun ...

Tips for retrieving the text value on keyboard enter press without triggering form submission

I am currently working on a feature where hitting the Enter key in a textbox should not automatically submit the form. The textbox is located within a form: @Html.TextBoxFor(model => model.ID, new { @class = "form-control input-sm", placehold ...

Creating a two-column post loop in Wordpress is a great way to display content in a

I've been attempting to separate posts for a long time without success. No matter what variations I try, the result is always either a single post or duplicating all of them. In other words, multiple posts are not displaying as intended. If anyone ha ...

Troubleshooting: CSS causing images to not show up on

Struggling with a CSS issue, I can't seem to solve it. My images are not showing up on the webpage even though the URLs are correct and the HTML is properly written. There is no specific styling applied to the images, and the only styling for the ima ...

Having trouble viewing a dynamically adjusting Angular NVD3 graph embedded in bootstrap

I have been utilizing the NVD3 library along with bootstrap 3.0 for my project. I have two divs with the classes "col-md-6 col-sm-12" positioned side by side. My goal is to showcase charts in both of these divs. To ensure that the charts are displayed corr ...

Clicking on a link with JQuery does not fire the action when the href attribute is set to "#open-site"

My navigation setup is as follows: <ul> <li><a href="index.html#open-site">Test</a></li> <li><a href="#open-site">Test</a></li> <li><a href="test.html#open-site"> ...