Issue with Jquery Selector: unable to target element when clicked

I'm currently working on a project where users can select elements from one box and they will show up in the next box. The issue I'm facing is when I click on a shortlisted element, it doesn't behave as expected.

Below is the code snippet:

HTML:

<div id="secondbox">
    <div class="elements">
        Soni
    </div>
    <div class="elements">
        Soni1
    </div>
    <div class="elements">
        Soni2
    </div>
    <div class="elements">
        Soni3
    </div>
</div>

JQ:

$(".pink").click(function()
    {
        //$(this).remove();
        alert("Hi");
    });
    $(".elements").click(function()
    {
        if($(this).attr("class")=="elements")
        {
            $(this).clone().appendTo("#firstbox").addClass("pink");
            $(this).addClass("red");
        }
    });

CSS:

#secondbox,#firstbox{float:left;height:300px;width:300px;border:1px solid black;}
.elements{width:90%;margin:5px;border:1px dashed orange;}
.red{background-color:#d5d5d5;}
.pink{background-color:#BCED91;}

Please assist in resolving this issue.

Answer №1

When generating elements dynamically in the second list, it is important to utilize .on() for binding the click event.

$(document).on('click',".pink",function () {
    $(this).remove();
    alert("Hi");
});

Check out this jsFiddle example

As mentioned in the documentation for .on():

Event handlers are only attached to currently selected elements; they must be present on the page when calling .on(). To ensure that elements can be selected and bound, it's recommended to perform event binding inside a document ready handler for elements existing in the HTML markup of the page. If new HTML is injected into the page, select the elements and attach event handlers after the new HTML has been inserted.

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

Setting the second tab as the primary active tab

I am currently working on a script that is well-known, and everything is functioning perfectly. However, I want to change it so that when the page is first opened, it displays the second tab instead of the first one (the first tab being a mail compose tab ...

Adding the text-success class to a Bootstrap 5 table row with zebra striping does not produce any noticeable change

I am encountering an issue with a Bootstrap 5 table that has the class table-striped. When a user clicks on a row, I have implemented some jQuery code to toggle the class text-success on the row for highlighting/unhighlighting purposes. The highlighting f ...

Loading stylesheets from node_modules before rendering in Angular

I have successfully installed Ionicons in Angular 9 by running npm install --save [email protected]. In order to use them, I imported them into my styles.scss file as shown below: $ionicons-font-path: "~ionicons/dist/fonts"; @import "~ionicons/dist/s ...

The hover action in the Jquery Accordion does not activate when a section has been opened before

I'm facing a problem with my jQuery accordion menu. After opening and closing a section, the ':hover' effect stops working only for that specific section. However, it continues to work for other sections that haven't been clicked yet. ...

The functionality of the Datatable column select filter sort() is malfunctioning when there is a link present

I am encountering an issue with the datatable column select filter. One of the columns in my table contains HTML link tags, which is causing unsorted select options to appear at the top. <th><a href="{{route('customer.information', ...

Creating a dynamic navbar with Python (Django), HTML, CSS, and Javascript for a fully responsive

I am currently utilizing a guideline to develop a responsive navbar that adapts its layout based on the screen size. It will display elements in a dropdown list for smaller screens, as opposed to an inline layout used for larger screens. Here is a snippet ...

The hover effect is not altering the color

$(document).ready(function() { $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 200) { $(".nav-bg").css({ "background": "#fff", ...

What causes the entire webpage to shift when adjusting the margin-top value?

As I work on creating this website based on a tutorial, it's clear that I am still in the learning stages. Unfortunately, the tutorial didn't provide an explanation for the unexpected behavior I'm experiencing. Here's the CSS code snip ...

How can you make the jQuery popup bar hidden by default?

Recently, I came across a tutorial on creating a popup bar similar to the one you see at the top of many websites. Interested in learning how it's done, I followed this tutorial: Being new to jQuery, I had a question in mind - is it possible to have ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

What is the best way to eliminate double quotes from an angular expression?

I am in need of the following: <div><div> May I assist you </div></div> The content of the inner div should be generated by the Angular controller: <div> May I assist you </div> Therefore, my HTML code will now look ...

Tips for extracting the image URL from my JSON string

I am in possession of a json file that includes URLs for images, and I have come across something that seems to be a URL, which is encoded as: iVBORw0KGgoAAAANSUhEUgAAADYAAAAzCAMAAADrVgtcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6m ...

Challenges associated with Bootstrap toggle switch

I am having some difficulties with using bootstrap switch. I have tried the examples provided on , but regardless of the classes I apply, the buttons remain the same small size and the text for ON and OFF is barely visible. I can't seem to figure out ...

An HTML component experiencing a problem with font-size display

Currently, I'm encountering an issue with the font size in my PDF report when rendering an embedded HTML component using the following Java code: Snippet of my Java code : StringBuilder htmlBody = new StringBuilder(""); htmlBody.append("<p class= ...

Angular Data Tables: A guide to fetching data from selected rows for editing or deletion

When I click on the edit/delete button in each row of the table, I want to be able to determine which row's data I have selected so that I can make edits or deletions and then update it in my database. Can someone please provide guidance on how to ac ...

Demonstrating various elements within an application using Vue3

I created two components and attempted to display them in a Vue 3 application. Here is my HTML code: <div id="app"> <image_preview> URL: [[image]] </image_preview> <file_uploader> Counter:[[coun ...

Is there a way to attach an event for multiple arithmetic operations to a checkbox?

My form includes 4 checkboxes for different mathematical operations. <form action="" method="POST"> Select number of questions: <input type="number" name="que" value="que"> <br> <br> Select number of series: <select name="sel ...

Challenges encountered when utilizing JQuery in conjunction with node.js

I recently set up node.js on my Windows 7 system and attempted to run a simple JQuery script called a.js. The script consists of the following code: require("jquery"); $().jquery; However, I encountered an issue when trying to run this with JQuery. It re ...

Getting the value of a variable inside an onclick function

I am facing an issue with displaying the values of 2 variables inside an onclick event. I have tried the code below but it is not working. Can someone please help me solve this problem within the next 3 hours? var myCode = "12345"; var myCount = "5" $(&a ...

Guide on converting jQuery code to AngularJS

Implementing Quantity Increment and Decrement Operations for Multiple Rows in AngularJS 1.x with ng-repeat Struggling to translate jQuery code into AngularJS? Here's a comparison between jQuery and AngularJS implementations for quantity increment and ...