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: https://i.sstatic.net/4yQ6U.png

After deleting Filter 1, the state changes to: https://i.sstatic.net/s52MO.png

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

https://i.sstatic.net/8AJSx.png 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

The ng-show and ng-hide directives are not working as expected, and there are no error

I'm currently working on a Todo App using AngularJS 1.x (version 1.6), but I'm having issues with ng-show and ng-hide functionality. The aim is to have a text box appear in the todo section when the edit button is clicked to modify existing todos ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

Is it possible to add a computed value to the bar's end in Chart.JS?

I'm creating a bar graph that has two bars representing different weeks. Currently, it looks like this: https://i.stack.imgur.com/6Avni.png However, I want it to look like this: https://i.stack.imgur.com/TAVqe.png In order to achieve the desired r ...

What could be causing the issue with my css `content:` not functioning across different browsers, and how can I enhance cross-browser compatibility in all cases

Working on my first HTML/CSS project, I encountered a browser compatibility challenge. The code functions well in Firefox, IE, and Edge but fails in Chrome. Specifically, I am trying to make a button display alternating up and down arrows when clicked. Whi ...

Dynamic fields added using JavaScript are not recognized by PHP

I have a MySQL database where orders are stored along with various activities. My PHP/HTML page retrieves these activities when an order is clicked and allows users to modify them using a form. Upon submission, another PHP file updates the database by loop ...

Identifying when an image element is within the viewport using jQuery Mobile

Looking for a solution to bypass the image size download limit on mobile devices by detecting when an image is in view and then downloading it. Also interested in replacing the image src with a smaller image to free up memory. Any tips on how to efficientl ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Is JQUERY always setting MVC bool EditorFor value to true?

I am facing an issue with a boolean value on my form: <div class="form-group"> @Html.LabelFor(model => model.IsMonday, "Monday", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.Editor ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

Tips for Updating Information within a Table with the Help of jQuery, AJAX, PHP, and MySQL

I need some assistance! Here's the scenario: There are two tables containing data from the database. The number of tables varies based on the user posting them. I utilized a "while loop" to display the table with data on the page. Now, I want the d ...

How do I submit an array of objects in Laravel?

I am currently working with a dynamic table that allows users to add and delete rows. Each row contains input fields where users can enter data for an object. At the moment, I am manually assigning index numbers to the name attribute like this: <input ...

Extracting user's clicked username to store in the database

I'm currently working on a script that allows users to mention others, but I've hit a roadblock. Each user can select another user by clicking on their name, which then adds the username to a designated div. Users can also input additional text ...

Updating Navigation Bar Font

I am a novice in the process of constructing my own navigation bar for my website, and I am encountering difficulties when trying to customize the font (color, font-family, etc). Currently, the links in my navigation bar (such as home, contact, store, etc ...

`Uniform background color across all pages`

My goal is to allow customers to select a color that will persist across different pages on the website. The code below shows how users can choose a color on the first page: <select id="color" style="width: 5%; height: 10%" size="5"> ...

DiscordJS bot using Typescript experiences audio playback issues that halt after a short period of time

I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing. Bel ...

Blurring and masking an image within a hollow circle shape

I'm currently working on developing a similar example using react-native-svg. The background image I am using is dynamic and needs a transparent circular mask. Additionally, I want to apply a blur effect to that specific section of the background ima ...

Dropdown menu change event malfunctioning

I am facing an issue with my HTML form that contains multiple text fields and dropdowns. I need to loop through all the dropdowns for validation purposes. Initially, only the first dropdown is visible when the page loads. The rest of the dropdowns become v ...

Access the value of a variable from a window resizing event and utilize it in a different

I have a carousel that I'm working with and am trying to figure out how to announce the number of currently visible slides when the "next" button is clicked. While I can see that on resize, the correct number of slides is being logged, I am strugglin ...

Struggling to update the state of an array using ReactJS and unsure of how to iterate through it

Currently, I am in the process of developing a movie voting application for me and my friends using React. I have made significant progress but I am facing issues with setting or updating the state of the 'rating' object. The structure of the ar ...