0

I having problems when applying the toggle to my divs. These divs are created after an ajax call which fetches data and creates the divs. After this, I'm applying the toggle for these divs by calling activateToggles(). So far, everything works fine. However, if I click 'load more' which will fetch the next 10 rows, the ajax will append more divs on the page, the new divs will have the correct behavior but the previous ones will toggle twice, meaning they will expand and contract. If I load more, then the initial ones will toggle x3, next ones x2, and new ones would be ok.

I believe the problem is when the activateToggles() it shouldn't assign a toggle to the divs that already have it. But how do I check this?

  function activateToggles() {

        jQuery(function () {
            jQuery(".medical-details").hide();
            jQuery(".toggle").click(function () {

                var that = jQuery(this);

                    that.next().toggle("fast", function () {       
                    });
            });
        });
    }
alwaysVBNET
  • 3,150
  • 8
  • 32
  • 65
  • Post a [mcve] please – j08691 Oct 12 '16 at 14:36
  • Use delegated event handlers instead. – adeneo Oct 12 '16 at 14:36
  • This is an example of an X/Y problem. You do not need to test that toggle is activated on each div, you need to delegate the event handler to a static parent container. – mplungjan Oct 12 '16 at 14:41
  • @mplungjan could you please give me an example? Do you mean like this: .jQuery(".toggle").on('click', 'a.myclass', function() ? – alwaysVBNET Oct 12 '16 at 14:46
  • 1
    Yes. Like this `$("#divContainer").on("click",".toggle",function () {` - if you do not have a container `$(document).on("click",".toggle",function () {` will do it too and this is shorter: `$(this).next().toggle("fast", function () { });` if you do not need "that" – mplungjan Oct 12 '16 at 14:56

0 Answers0