Problems with Append and slideToggle

0

I have a problem here that is as follows. I have a timeline that displays some posts, for ajax I load more content and make an append, the new items that are displayed do not get the slideToggle. I've manually added the script again on the page that is sending the content by ajax and slideToggle works, the problem is this, when it opens, it already closes quickly and does not let the div on the display, does anyone know how to solve it? I already put display none and it did not solve.

$("#maisPostagens").click(function (event) {
    event.preventDefault();
    $("#carregando").toggle();
    var posts = $(".postagens:last").attr("lang");
    if (posts) {
        var url = '_funControllers/exibePostagensLinhaDoTempo.php?posts=' + posts;
        setTimeout(function () {
            $.get(url, function (dataReturn) {
                $("#carregando").toggle();
                $(".auto").append(dataReturn);
            });
        }, 1000);

    }
});
//efeito de aparecer e esconder divs de Comentários

$(".auto .postagens .comentarios .linkComentario").on("click", function (event) {
    event.preventDefault();
    $(this).parents('.externa').find('.comentarioPost').slideToggle();

});

Thank you

    
asked by anonymous 20.01.2016 / 16:57

1 answer

1

In event click you can do so:

$(document).on("click", ".auto .postagens .comentarios .linkComentario", function (event) {
    event.preventDefault();
    $(this).parents('.externa').find('.comentarioPost').slideToggle();
});

When the element is dynamically created, a very good technique is to define it after the event, as in the example above, and assign the event to document or the "parent of all" element.

Example without the technique

$('button').click(function(){
$('body').append('<div class="box"></div>');
})

$('.box').on('click', function(){
	$(this).css('background', '#fff')
})
.box{
  width: 200px;
  height: 200px;
  background: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button>adicionar</button>

Noticethatdivsarecreateddynamically,andclickdoesnotwork.

Examplewiththetechnique

$('button').click(function(){
$('body').append('<div class="box"></div>');
})

$(document).on('click','.box', function(){
	$(this).css('background', 'red')
})
.box{
  width: 200px;
  height: 200px;
  background: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>adicionar</button>

Notice that the dvis with the click event react to it now.

    
20.01.2016 / 17:17