0

I'm facing a problem to delegate an event on click on new element created in jQuery.

My HTML:

<div id="add">Add row</div>
<form class="form-horizontal" id="list-items">
    <div class="panel-group item">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a class="accordion-toggle">Item number 1</a>
                </h4>
            </div>
            <div class="panel-collapse collapse">
                <div class="panel-body">
                    ...
                </div>
            </div>
        </div>
    </div>
</form>

My JS:

$('.panel-heading').click(function(){
    if($(this).next('.panel-collapse').hasClass('in')) {
        $(this).next('.panel-collapse').removeClass('in');
    }
    else {
        $(this).next('.panel-collapse').addClass('in');
    }
});

$('#add').click(function() {
    var newRow = $('.item').eq(0).clone();
    $('#list-items').append(newRow);
});

My problem is when a new element is create, I can't click it to open its content.

Could your please help me in it.

Thanks.

teamo
  • 443
  • 1
  • 7
  • 16
  • is your JS is Dom ready? – Shehary Jul 25 '15 at 15:53
  • question really shows a lack of research effort... you knew the `delegation` term...should have been very easy to research from there. SO should not be your first line of doing research – charlietfl Jul 25 '15 at 16:03

1 Answers1

2

Try event delegation as below to capture dynamic element's events:

$('.form-horizontal').on('click','.panel-heading', function(){
    if($(this).next('.panel-collapse').hasClass('in')) {
        $(this).next('.panel-collapse').removeClass('in');
    }
    else {
        $(this).next('.panel-collapse').addClass('in');
    }
});
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200