Add to and subsequently remove the possibility of deleting that element

I encountered an issue while moving elements from one div (x) to another div (y). The problem is that the elements in div x are deletable, but once they are copied to div y, they cannot be deleted.

Here is the initial state:

After deleting Filter 1, the state changes to:

In this state, after adding the Name person above, I am unable to delete it like the other elements.

I have reviewed the CSS classes and everything seems to be in order. Here is my code:

JavaScript

function AddFilters() 
{

    if ( $(".filter-edited").css('display') == 'none' )
    {
        $("#btn_add").html("Hide Filters");
        
        $(".filter-edited").fadeIn();
    }

    else if ( $(".filter-edited").css('display') != 'none' )
    {
        $("#btn_add").html("Add Filter");
        
        $(".filter-edited").hide();
    }

}

$(document).ready(function() {
    $('.removable').on('click', function() {
        $(this).parent().remove();
    });
});

$(document).ready(function() {
    $('.addable').on('click', function() {
        $(this).parent().appendTo(".filter-added");

        $(this).attr('class', 'glyphicon glyphicon-remove pull-right removable');

    });
});

HTML

<script src="../assets/own_js/addfilters.js"></script>

<div class="row add-filters">
    <div class="col-md-12">
        <div class="row ">
            <div class="col-sm-10 filter-added">


                <span> Filtered on: </span>
                <a class="btn btn-default">
                    <span class="text">Filter 1</span>
                    <span class="glyphicon glyphicon-remove pull-right removable" ></span>
                </a>
                <a class="btn btn-default">
                    <span class="text">Filter 2</span>
                    <span class="glyphicon glyphicon-remove pull-right removable"></span>
                </a>
                <a class="btn btn-default">
                    <span class="text">Filter 3</span>
                    <span class="glyphicon glyphicon-remove pull-right removable" ></span>
                </a>


            </div>
            <div class="col-sm-2 pull-right">
                    <a class="btn btn-default" id="btn_add" onclick="AddFilters()">Add filter</a>
            </div>
        </div>

        <div class="row filter-edited" style="display:none;">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-10 filters">
                        <a class="btn btn-default">
                            <span class="text">Business</span>
                            <span class="glyphicon glyphicon-plus pull-right addable"></span>
                        </a>
                        <a class="btn btn-default">
                            <span class="text">Campaign</span>
                            <span class="glyphicon glyphicon-plus pull-right addable"></span>
                        </a>
                        <a class="btn btn-default">
                            <span class"text">Event</span>
                            <span class="glyphicon glyphicon-plus pull-right addable"></span>
                        </a>
                        <a class="btn btn-default">
                            <span class"text">Channel</span>
                            <span class="glyphicon glyphicon-plus pull-right addable"></span>
                        </a>
                        <a class="btn btn-default">
                            <span class"text">Name person</span>
                            <span class="glyphicon glyphicon-plus pull-right addable"></span>
                        </a>

                    </div>
                    <div class="col-md-2">

                    </div>
                </div>
                <div class="row">

                </div>
            </div>
        </div>
    </div>

</div>

SASS CSS

 .add-filters
 {
    .filter-added 
    {
        span 
        {
            margin-right: 5px;
        }

        span.glyphicon.glyphicon-remove 
        {
            margin-left: 8px;
            color: red;
            &:hover
            {
                cursor: pointer;
                color:rgba(0,0,0,0.5); /*where 0.5 stands for 50% opacity*/
            }

        }

        a.btn.btn-default 
        {
            min-width:100px;
            padding: 3px 0px 0px 0px;

            margin-left: 10px;

            @media (max-width: 768px) {

                margin-left: 0px;

            }
            &:first-of-type
            {

                margin-left: 0px;
            }

            &:hover
            {
                cursor:default;
                background-color: #fff;
                border-color: #ccc;
            }

        }

    }
    .filter-edited 
    {
        margin-top: 20px;
        -webkit-border-radius: 7px; 
        -moz-border-radius: 7px; 

        border-radius: 7px; 
        border: 1px solid #ddd;


        span.glyphicon.glyphicon-plus
        {
            margin-left: 4px;
            color: #15925f;

        }

        a.btn.btn-default 
        {
            min-width:150px;
            padding: 10px 5px 10px 0px;

            margin-left: 5px;

            @media (max-width: 768px) {

                margin-left: 0px;
                margin-top: 2px;

            }
            &:first-of-type
            {

                margin-left: 0px;
            }
        }

        .filters {
            padding: 15px;

        }
    }
 }

Answer №1

Make sure you are only monitoring events on elements that are currently visible. To do this, use the .on() function on the parent element and specify the child selector as the second parameter.

$(document).ready(function() {
    $('.filter-added').on('click', '.removable', function() {
        $(this).parent().remove();
    });
});

Answer №2

  $(document).on('click', '.removable', function() {
      $(this).parent().remove();
  });

This adjustment is necessary because the original code only applies the click event to existing elements on the page. By using the modified markup above, the event is bound to all current and future elements with the class '.removable' that exist in the document.

An alternative approach would be to run a .bind() on the object after it is created, but this would require more code and be less efficient.

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

Failed to add a new entry to the Sharepoint 2013 List

Having trouble saving an item to a SharePoint list using Knockout.js and REST. In my Ajax POST request, I've used ko.toJSON but the entry doesn't show up in the SharePoint list. It's possible that I'm passing the wrong parameter value. ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

Having trouble with Ajax and facebox integration issues?

My website utilizes ajax jquery and facebox for interactive features. You can check out a demo here. The div with the ID "#content" contains links to other pages that open successfully using facebox. However, when I reload the content of this div using aj ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

Troubleshooting the 'App Already Bootstrapped with this Element' Error in AngularJS

When I try to load my AngularJS app, I encounter the following error: Uncaught Error: [ng:btstrpd] App Already Bootstrapped with this Element '<html lang="en" ng-app="app" class="ng-scope">' I have only placed ng-app once in the html elem ...

Utilizing Selenium Webdriver to efficiently scroll through a webpage with AJAX-loaded content

I am currently utilizing Selenium Webdriver to extract content from a webpage. The challenge I'm facing is that the page dynamically loads more content using AJAX as the user scrolls down. While I can programmatically scroll down using JavaScript, I a ...

JavaScript allows users to create a single string by merging multiple strings positioned at various points

Let's say we have 3 strings: s1 = "ab", s2 = "cd", s3 = "ef". The task is to form a new string by merging s1, s2, and s3. The twist here is that the user has the freedom to choose the positions of these 3 strings. For example: s1 - position 3; s2 - ...

Angular material table featuring custom row design

My team is working with a large table that is sorted by date, and we are looking to add some guidance rows to help users navigate through the data more easily. The desired structure of the table is as follows: |_Header1_|_Header2_| | 25/11/2018 | ...

Tips for incorporating animation while altering element styles within JavaScript

I am looking to incorporate a sliding animation that moves the element downward when the display property is set to block, and upward when it's set to none or an empty string, here is the current JavaScript code I have: <script> function showQ ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

What are some ways to utilize the <span> tag to apply distinct styles to specific characters within text compared to

Imagine I have a string like <p>hi my name is john</p>. I know that I can use the span element to target specific characters and apply different styles using CSS. But what if I want to style "name" and "john" differently from each other and the ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Error message "ag-grid: Unable to perform the key.forEach function in the console when resizing columns"

Within the application I am working on, I have implemented the ag-grid view. To address the issue related to the last empty pseudo column, I decided to resize the last displayed column using the 'autoSizeColumns' method of ag-grid. While this sol ...

Is it possible to embed an array within an object by utilizing the name attribute in a form?

I am currently developing a full-stack application where I have a form that submits data to one of my post routes. In this form, all input fields are grouped into req.body.model. This is made possible by adding a name attribute with square brackets around ...

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

Using jQuery to retrieve the values of two distinct sliders and executing a specific mathematical operation

I have two sliders with their own values and properties: https://i.stack.imgur.com/3OZqr.gif My goal is to retrieve the values of these two sliders and calculate a result that will be displayed next to the interest label. The calculation formula is: poun ...

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

Use an if-else statement in jQuery with selectors to determine if a specific div element has been added to it

What if you have a main div and append one of these sub-divs to it? For example: <div class ="append"> <div id ="one"></div> <div id ="two"></div> </div> Then in jQuery, could you do something like this: if ($(.a ...

Unusual behavior being exhibited by the background in an HTML5 canvas

I have an 800 by 100 image for the background and I'm trying to extract sections from it (like a sprite sheet) in order to create a background. I believe this method is efficient and allows me to experiment and learn how to generate backgrounds in the ...