Attach to dynamically generated elements by event listeners that bind on mouseover or hover

I am looking to implement a hover effect for dynamically generated items in JavaScript. Specifically, when I hover over an icon element, I want a unique text to appear related to that icon:

for (var i = 0; i < items.length; i++) {
    $('.items').append('<div class="icon' + i + '"></div>');
    $('.itemInfo').append('<div class="info' + i + '">' + name + '</div>');
}

I have tried using jQuery's .hover() and .on() methods to show the info when hovering over the icon, but I encountered issues with getting the correct info displayed. I also attempted to hide the info initially and show it on hover, yet nothing appeared. Despite the debugger indicating that the function was being triggered, the correct index was not captured.

for (var i = 0; i < items.length; i++) {
    $('.items').append('<div class="icon' + i + '"></div>');
    $('.itemInfo').append('<div class="info' + i + '">' + name + '</div>');

    $('.icon' + i).on({
        mouseenter: function () { $('.itemInfo' + i).show(); },
        mouseleave: function () { $('.itemInfo' + i).hide(); }
    });
}

It's worth noting that the icons and info are kept separate in different divs for styling reasons. While the current structure works for a known number of items, I am unsure how to handle cases where the number of generated items is unknown. I'm contemplating whether merging the icon and info elements into a single div would be a better solution in such situations.

Answer №1

As stated in Jeromy French's comment, utilizing event delegation is the key.

If my understanding is correct, this jsFiddle example should meet your requirements.

var elements = ['first', 'second', 'third'];

for (var i = 0; i < elements.length; i++) {
    $('.elements').append('<div class="icon' + i + '">Item ' + (i + 1) + '</div>');
    $('.elementInfo').append('<div class="info' + i + '">' + elements[i] + '</div>');
}

$('.elements').on('mouseover', "div[class^='icon']", function(evt){
    var id = evt.currentTarget.className.split('icon')[1];
    $('.info' + id).show();
});

$('.elements').on('mouseout', "div[class^='icon']", function(evt){
    var id = evt.currentTarget.className.split('icon')[1];
    $('.info' + id).hide();
});
div[class^="info"] {
    display: none;
}

.elementInfo {
    background-color: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements"></div>
<div class="elementInfo"></div>

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

Utilize a map image as a texture on a plane within a personalized shader in THREE.js

I'm currently facing an issue where I need to load two images as textures, blend between them in the fragment shader, and apply the resulting color to a plane. However, I am struggling to even display a single texture properly. My process for creatin ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

Tips for implementing a collapsible sidebar within a single div element

Imagine a scenario where there is a div serving as a container for a sidebar on the left and main content on the right. The goal is to create a collapsible sidebar navigation, allowing users to hide or display the sidebar with the click of a button. Desp ...

Tips for enabling item draggability following AJAX filtering operations

I have a draggable list of names that can be filtered using checkboxes. When a checkbox is checked, an ajax call is made to filter the names. The list is displayed in an accordion format as shown below: <div id="myAccordion"> <?ph ...

Protractor is displaying an error message of "unable to locate element testability" when attempting to access an element

I'm encountering an issue with Protractor while trying to access a variable that stores the return value of "elements.all". As someone who is new to Protractor, I wasn't sure how to select elements by a custom attribute. Thankfully, I received so ...

When refreshing, jsTree should automatically expand all nodes

I have been attempting to expand all the nodes in my JSTree after refreshing it, but so far I have been unsuccessful. $('#'+messages.Instance_Name).jstree(true).settings.core.data = interfaceNode; $('#'+messages.Instance_Name).jstree ...

What is the best way to position the sign-in modal form on the top right corner of my website?

Hey there, I'm facing a bit of an issue and can't seem to figure out what went wrong. Recently, I inserted a Bootstrap Sign In modal in my HTML file. Here's the code: <div class="text-center"> <a href="" class ...

Steps for adding a variable to a JSON request

I'm new to JavaScript and React Native and I'm looking for a way to include variables in a JSON request. Specifically, when making a JSON request using Fetch or Axios to a URL, I need to customize the URL based on certain parameters. For instance ...

Disappearing Data: Struts2 Autocompleter's Entries Vanishing Upon Submit Button Click

I am currently utilizing the auto-complete feature from The issue I am facing is that when I type "Ball", the auto-complete suggests "Balloon". Even though both "Balloon" and "Balloon" appear in the text field and the list, when I click elsewhere on the s ...

Is recursion effective in this scenario? (javascript/node.js)

Currently, I am working on creating a TV using a Raspberry Pi and JavaScript to play the same playlist repeatedly. Although playing the files is not an issue, I am facing a challenge with the asynchronous nature of JavaScript. Below is the code that is cau ...

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

SQL query using Ajax

I'm currently working on an Ajax call using a query string, but I've hit a roadblock midway through. My goal is to update a SQL table with the JavaScript sortable function. After an item has been moved up or down, I want to pass it through Ajax a ...

The row count feature is ineffective in Materialize CSS when adjusting the text area

Can the row count of a text area in materialize css be initialized with a specific number using "rows='20'"? How can we adjust the default row count? Here is an example of code that attempts to set the row count but doesn't work: <div c ...

"Windows Phone Users Experiencing Issue with Website Scroll Functionality

My latest project involved creating a responsive website with nodejs integration, and it performs well on various devices. However, a problem arises when viewing the website on the Windows Phone IE browser - the webpage refuses to scroll down. The cause o ...

Transitioning classes in Vue elements

Is it achievable to create a smooth transition between two CSS classes with different background images? That's the challenge I'm currently facing. Here is the Vue code snippet I am working on: <div id="flip-list-demo" class="demo"> & ...

Status and route redirection in Vue instance management

I am looking to establish a global status property for my application using vue.js and vue-router. This property should be shared between components and used to control access to certain routes based on its value. For instance, I want to redirect all rout ...

Guide for implementing a one-line if statement in Javascript

I am aiming to assign a class using a single-line if statement as outlined in this source. Currently, I am utilizing Material-UI and attempting to specify a class. Therefore, I would like to implement this approach: if(condition) expression <Typogr ...

Replacing text within a paragraph using D3.js

Is it possible to develop a D3 function that can choose a paragraph, delete its content, and replace it with new text? If so, what would be the most effective way to accomplish this? I attempted the following: d3.select("#triggerButton") .on("clic ...

Steps to eliminate a list-divider in jQuery Mobile when removing the list item

I need help with a situation involving groups of list items (li). When I delete all the "li" in a group, I want to also remove the list-divider that separates them. For example, if there are 3 "li" after a list-divider, and I delete each "li" one by one, w ...