Home > Software design >  Create click event on newly appended buttons with JQuery
Create click event on newly appended buttons with JQuery

Time:07-30

I want to create alerts that can be hidden, but when I hide one, they are all hidden at the same time.

Alerts

This is the code I have, where I need to create the "click" event to hide only the newly created button but hide all of them at the same time:

const newAlert = $("#mainBodyContainer").append(`
        <div >
            <p>
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <span>a</span>
            </p>
            <strong >&times;</strong>
        </div>
        `);

const deleteAlertButton = newAlert.find(".alert-del")
deleteAlertButton.on("click", () => {
    deleteAlertButton.parent().addClass("hidden");
});

CodePudding user response:

Docs jQuery find: "Get the descendants of each element in the current set of matched elements"

Keyword: elementS.

You don't have a unique selector. Every time you create a new button, your event handler returns ALL .alert-del classes it finds inside #mainBodyContainer. Including the ones already in there.

To solve the issue, make sure each button can be uniquely selected:

let alerts = 1;

function createAlert()
{
  const newAlert = $("#mainBodyContainer").append(`
    <div >
      <p>
        <span>Button ${alerts}</span>
      </p>
      <strong id="alert_${alerts}" >&times;</strong>
    </div>
  `);
        
  const deleteAlertButton = $("#alert_" alerts);
    deleteAlertButton.on("click", () => {
      deleteAlertButton.parent().addClass("hidden");
    });

    alerts  ;
}

createAlert();
createAlert();
createAlert();
.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainBodyContainer"></div>

  • Related