How to make slideToggle () of div that was requested via ajax?

0

Dear Sirs,

I have a div that is populated via ajax:

    function atualizaConteudo(){
        $.ajax({
            url: 'getters/conteudo_amanha.php',
            success: function(data) {
                $('#conteudo_amanha').html(data);
            }
        });
    }
    atualizaConteudo();

The div looks like this:

    <div id="conteudo_amanha">
        <button type="button" class="novo-detalhe" data-id_conteudo="4">
            Mostrar conteudos
        </button>
        <div id="conteudo_4" style="display: none">
            Conteudos recuperados
        </div>
    </div>

I try to make slideToggle ():

    $('.novo-detalhe').on('click',function(){
        var id_conteudo= $(this).data('id_conteudo');
        $('#conteudo_'+id_conteudo).slideToggle();
    });

I need the div retrieved via ajax (#content_4), is hidden / shown when the user clicks the button, I put the div inside the page (instead of using ajax to insert inside div # conteudo_amorrow), it worked , but I am not able to make it work using the ajax request.

I'm new with ajax and jquery ...

    
asked by anonymous 27.12.2017 / 19:30

2 answers

0

When the element is created after the DOM has been fully loaded, jQuery event delegation usually does not work.

For delegating events of dynamically created elements, use the following code:

$(document).on('click', '.novo-detalhe', function () {

     var id_conteudo = $(this).data('id_conteudo');

     $('#conteudo_'+id_conteudo).slideToggle();
})

This will basically cause all elements that have class novo-detalhe to trigger the click event, whether they are created dynamically or not.

When delegating events to dynamic elements, you always have to set the parent element, which is fixed in the document, as the selector, so you can define the children that will be dynamic. In our case, we use document , because it is the "root" of the whole document, but we could use another element as the basis for dynamic delegation, in this case #conteudo_amanha , which seems to be fixed in your case. >

Being the "parent" who receives the dynamic "children", we could do this:

 $("#conteudo_amanha").on('click', '.novo-detalhe', function () {
     // faça sua mágica acontecer aqui
 })

Note : The above answer solves your problem, but it is not the best way.

Take a look at this question from the English Stackoverflow:

17.08.2018 / 15:35
0

I already had an equal problem and I solved it like this:

function atualizaConteudo(){
    $.ajax({
        url: 'getters/conteudo_amanha.php',
        success: function(data) {
            $('#conteudo_amanha').html(data);
            $('.novo-detalhe').on('click',function(){
                 var id_conteudo= $(this).data('id_conteudo');
                 $('#conteudo_'+id_conteudo).slideToggle();
            });
        }
    });
}
atualizaConteudo();

The onclick should be set after the content has been loaded.

    
17.08.2018 / 12:13