0

I have list on my website like this:

<ul id="listProfiles" class="list-group">
    @foreach($profiles as $profile)
    <li class="list-group-item" profileId="{{ $profile['id'] }}">{{ $profile['name'] }}</li>
    @endforeach
</ul>
<div id="profileResult"></div>

When I add new element to this list using function below:

$("#addNewProfileButton").on("click", function () {
    profileName = $("#newProfileInput").val();
    $("#newProfileInput").val('');
    $.ajax({
        method: 'GET',
        data: {
            profileName: profileName
        },
        url: '/addNewProfiles'
    }).success(function (newProfile) {
        console.log(newProfile);
        $("#listProfiles li:last").after('<li class="list-group-item" profileId="' + newProfile.id + '">' + newProfile.name + '</li>');

    }).error(function (msg) {
        console.log(msg);
    });
});

it's added properly but not clickable using this:

$("#listProfiles li").click(function () {
    profileId = $(this).attr('profileId');
    $.ajax({
        method: 'GET',
        data: {
            profileId: profileId
        },
        url: '/spiderProfileDetails'
    }).success(function (msg) {
        $('#profileResult').html(msg);
    }).error(function (msg) {
        console.log(msg);
    });
});

All other elements are clickable. New element becomes clickable after refreshing the website. How to make it work without refreshing?

Bart
  • 23
  • 2

1 Answers1

5

$("#listProfiles li").click() adds the event listener on the selected elements, i.e. the elements that exist at that moment. New elements won't get affected by this.

The best way to solve this is to use event delegation. You can view this as a form of "dynamic event listening":

$("#listProfiles").on("click", "li", handlerFunction);

The event listener is registered on the listProfiles element, but the handler function is only invoked if the event originated on an element that is matched by the selector passed as the second argument to the on() method. This way it will include elements that are added later.

Lennholm
  • 6,177
  • 1
  • 15
  • 26
  • Well, how is that different from what I have commented above? ;) – Milan Chheda Aug 07 '17 at 13:12
  • 2
    @MilanChheda It's a proper answer and a proper explanation of both the issue and the solution, that's how it's different – Lennholm Aug 07 '17 at 13:14
  • 2
    Comment != Answer. If you only leave a comment without answering, people do not have a choice to upvote you for rep. – Terry Aug 07 '17 at 13:14