0

When I click on and element with a class of tool the alert box should show up but nothing happens, no errors in the console either.

I'm pretty sure the issue I'm seeing is an event delegation issue, I just can't figure out where I'm going wrong.

So the first snippet, the if statement loads a bit of HTML into the #tools element and the second snippet is when a user clicks on an individual .tool element that was loaded into #tools.

I've tried adding the alert code block into the if code block but didn't make a difference.

Snippets

if ($("#tools").length) {
    data = {}
    data['id'] = $("#tools").data('id');

    ajaxCall("#tools", 1, data);
}

$("#tools .tool").on("click", function(e) {
    alert("1234");
    e.stopPropagation();
});

HTML Example

<div id="tools"></div>

<div id="tools">
    <div class="tool">1</div>
    <div class="tool">12</div>
    <div class="tool">123</div>
    <div class="tool">1234</div>
</div>

*AJAX Function**

function ajaxCall(element, callId, dataIn)
{
    var limit;
    var data;
    data = {id: callId, data: dataIn, element: element};

    $.ajax(
    {
        type: "POST",
        url: "calls/",
        data: data,
        success: function (data)
        {                
            $(element).html(data);
        },
        error: function (jqXHR)
        {
            $(element).html(jqXHR.status + " - " + jqXHR.statusText);
        }
    });
}
llanato
  • 2,508
  • 6
  • 37
  • 59
  • 1
    You're right, it's an event delegation problem. You need a delegated event handler Note that using `on()` alone is not a delegated handler. You need to call it in the right way: `$('#tools').on('click', '.tool', function(e) { ...` – Rory McCrossan Jan 20 '20 at 14:14
  • Also the first `if` statement can be reduced to just `if ($("#tools").length) { ajaxCall("#tools", 1, { id: $('#tools').data('id')); }` – Rory McCrossan Jan 20 '20 at 14:15

0 Answers0