Shine a spotlight on elements that match with jQuery using live() or on()

Check out my jsFiddle demonstration where I have created a button that adds elements and provides links to delete these elements. Instead of actually deleting the elements in this example, I want to make it so that hovering over the (remove) link, which is generated by clicking the button, highlights the element with the corresponding "number" attribute.

I attempted to use both live(); and on(); for this functionality, but neither worked because the items are added dynamically after the initial page load.

I now prefer using on(); as jQuery has advised:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

This is my jQuery code:

    function numbers() {
        return $('#links span').length;
    }

    $('#add').on('click', function () {
        $('#links').append('<span number="' + (numbers() + 1) + '">Remove element ' + (numbers() + 1) + '</span><br />');
        $('#elements').append('<div number="' + numbers() + '" class="element">Element ' + numbers() + '</div>');
    });

    $('#links span').on('hover', function () {
        var number = $(this).attr('number');
        if ($('#elements .element').attr('number') == number) {
            $(this).addClass('highlight');
        }

});

Answer №1

To begin with, it is important to dynamically bind the events as elements are added dynamically. Additionally, using mouseenter and mouseleave events is recommended for toggling highlighting and tracking cursor movement. Lastly, I suggest utilizing data--attributes instead of a custom attribute like number.

function countNumbers() {
    return $("#links span").length;
}

$("#add").on("click", function () {
    var number = countNumbers() + 1;
    $("#links").append("<span data-number='" + number + "'>Remove element " + number + "</span><br />");
    $("#elements").append("<div data-number='" + number + "' class='element'>Element " + number + "</div>");
});

// Dynamically bind mouseenter and mouseleave events to apply to dynamically added elements
$("body").on("mouseenter", "#links span", function () {
    var number = $(this).data("number");
    $(".element[data-number='" + number + "']").addClass("highlight");
}).on("mouseleave", "#links span", function () {
    var number = $(this).data("number");
    $(".element[data-number='" + number + "']").removeClass("highlight");
});

VIEW FIDDLE

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

Exploring the benefits of utilizing Scoped CSS for individual components within Next.js version 13

Switching from a Vue.js background to starting with Next.js, I want to scope my CSS for each component such as Navbar instead of using it inside Globas.css. Is there a way to achieve this? I am also utilizing the Tailwind CSS library. I attempted creatin ...

Leveraging ForEach to merge two arrays and generate a fresh entity

I am in search of my final result which should be as follows: result = [{x: '12/12', y: 90 }, {x: '12/11', y: 0}, {x: '12/10', y: 92}, {x: '12/9', y: 0}, ... ] Currently, I have two arrays to work with. The first a ...

Why is it that aligning items in a row doesn't seem to function properly when I apply a custom class to a container-fluid in Bootstrap 4?

Recently, I started delving into the world of front end development. After mastering the basics of HTML5 and CSS3, I ventured into Bootstrap 4. My current project involves creating a replica of the Facebook login page. To achieve a full-width design, I uti ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

To insert a <div> element within a <tr> element while preserving the exact position of the <tr> tag - here's how you can do it:

I have a challenge with my table where I need to add a green progress bar in the form of a div element within a tr. The width of this progress bar should change dynamically from 0% to 100%, reflecting the current runtime of the video associated with that p ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

I attempted to access $.cookie but it appears to be malfunctioning

I found cookie.js on GitHub at https://github.com/carhartl/jquery-cookie and incorporated it into my code like this: $(document).ready(function(){ $("#abc").click(function() { var a = $("#text").val(); var b = $("#password").val(); alert("asdasdsd ...

Encountering the error "Unable to read the offset property of undefined" during a touch event

I'm currently working on integrating a color picker within an Angular application and have been trying to make it compatible with touchscreens. However, I've encountered an issue within the mousedown handler of the code. The problem arises when i ...

Aligning text in the center of a header, positioned beside an image

I am facing an issue with centering text within a banner. The banner is divided into 12 columns, with a cross icon placed in the left-most column for closing the window. However, the text is not centering within the whole banner width but only within the s ...

The returned JSON object lacks a specified name

After receiving the JSON data from the server, I noticed an unnamed node within the 'someStuff' object: { "someStuff": { "": { "foo": 0 }, "moreStuff": { "foo": 2 } } } This raises ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

Transform a PDF document into a Google Doc utilizing the capabilities of the Google Drive API version 3

I successfully uploaded a PDF file to Google Drive using a node server. However, I am struggling to find a way to convert it to a Google Doc format so that it can be downloaded later as a DOCX document. Here is the code snippet I've been working with ...

JavaScript overlay that does not interact with HTML elements directly

Currently, I am facing the challenge of implementing a javascript overlay upon page load without direct access to the html code. My only options are to upload .js and .css files. I have extensively searched for solutions, but as someone with limited exper ...

Tips for maintaining the navigation tab's consistent appearance

Whenever I click a button on the sidebar and the current tab is the second tab, the navigation bar switches to display the first tab. How can I prevent this switch and keep the second tab displayed when clicking a button on the sidebar? The code for this ...

The Material UI Drawer stays closed despite the state being set to true

Currently, I am in the process of developing a WebApp utilizing React and Material UI. Despite following numerous tutorials on implementing the Drawer component and poring over the documentation, I am still struggling to grasp its functionality. Even thou ...

Is it possible for a kraken.js backend to manipulate the content of a webpage?

Currently using kraken.js, which is an express.js framework, to construct a localized website. Within the header section, there are 3 language options provided as links. FR | EN | DE My goal is to have the link corresponding to the currently set locale ( ...

Is there any variation in the Stripe payments Workflow when utilizing the Connect-API?

I have a question about simplifying the implementation of the Stripe API for multiple products on a single page. Currently, I have a webpage with 20 different items and I am utilizing Stripe Connect. Instead of creating individual forms for each product i ...

What steps should be taken to refresh a page following an AJAX file upload?

I need some help creating a progress bar to track file uploads on my website. Here's what I have so far: HTML: <form action="upload/files.php" method="post" enctype="multipart/form-data" id="frmUpload"> <input type="file" name="upfile" ...

a single column with a div of varying height using flexbox

I need to create a div with a height of 120px using only the CSS property display: flex. I am not allowed to use float and can only use div elements. Here is the code I have so far, but I'm unsure how to achieve the desired outcome: .flex-containe ...

Adjusting the width of a select box to match the size of its child table using CSS

Within my Vue application, I've implemented a select box that contains a table component. When the select box is clicked, the table becomes visible in a container. However, I'm facing an issue where I can't dynamically adjust the width of th ...