Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Twitter Bootstrap Collapse work on dynamically loaded html using ajax

I am loading html using ajax call, this html has Bootstrap Collapse. The issue is Collapse is not working, if you click it will expand but it won't collapse again.

To check if I am doing something wrong, I put the same code on a static page (not loaded using ajax) and it works fine. So its seems issue only with dynamically loaded html.

I tried manually enabling Collapse using

$(".collapse").collapse() 

but still same issue.

I guess I need to use jquery's live() / on() methods, because the html is dynamic, but not sure how do I do that for calling $(".collapse").collapse() because I think it only works on events or is it something else that I need to do ?

like image 389
Abdullah Shaikh Avatar asked Dec 17 '12 08:12

Abdullah Shaikh


3 Answers

My solve is:

    $('.collapse').on('show', function () {
    var $this = $(this);
    if($this.attr('data-href'))
    {
        $this.html($.getJSON($this.attr('data-href'),function(data){
            $this.html(data.html);
            $this.removeAttr('style');
        }));
    }
    })
like image 31
NamPNQ Avatar answered Oct 22 '22 09:10

NamPNQ


i would suggest you to call

 $(".collapse").collapse() 

inside the ajax's success function after the dynamic html is appended.

like image 52
bipen Avatar answered Oct 22 '22 11:10

bipen


Just execute this on ajax success event.

$('[data-toggle="collapse"]').click(function(e){
      e.preventDefault();
      var target_element= $(this).attr("href");
      $(target_element).collapse('toggle');
      return false;
});
like image 1
barek2k2 Avatar answered Oct 22 '22 11:10

barek2k2