0

i have this func :

$(".card").each(function() {
  $(this)
    .closest('.collapse-group')
    .find('.btn')
    .toggle($(this).text().length > 16);
});

But I need to transform it when the elements are dynamically appended, for example i know how it to do for click func, but on EACH - no:

    $(document).on('click', '.btn', function(e) {
          e.preventDefault();
          var $this = $(this);
          var $collapse = $this.closest('.collapse-group').find('.collapse');
          $collapse.collapse('toggle');
        }); //- this func works

 $(document).on('each', ".card", function() {
      $(this)
        .closest('.collapse-group')
        .find('.btn')
        .toggle($(this).text().length > 16);
    });//??? - this func does not work

insert it right under the block where I append the cards does not work:

var card =
              `<hr>
            <h3>
          <p class="text-center " >${title}</p>
          </h3>
            <img class="col-12 ml-auto col-12 mr-auto" src=${images}>
            <div class="span4 collapse-group">
              <div class="text-center">
                <p><a class="btn btn-md btn-outline-dark btn-square" href="#">Check &raquo;</a></p>
              </div>
              <div class="collapse">
                <div class="card card-body">
                ${text}
                </div>
              </div>
            </div>`
            $('.container').append(card)
            $(document).find(".card").each(function() {
              $(this)
                .closest('.collapse-group')
                .find('.btn')
                .toggle($(this).text().length > 16);
            });
1
  • Put the each() logic in a function and then call that function right after you append the new elements. Commented Jul 20, 2018 at 6:44

1 Answer 1

1

each is not an event so cannot use with .on. Try below function to iterate cards

 $('.container').find(".card").each(function() {
       var toggle = $(this).text().length > 16;
       var collapseGroup = $(this).closest('.collapse-group');
       collapseGroup.find('.btn').toggle(toggle);
    });
Sign up to request clarification or add additional context in comments.

8 Comments

where are you appending the dynamic elements? you need to call above code right after it. can you try that
updated the body of the question, immediately below the appended block
please put ; after $('.container').append(card). I have updated my post, can you please try with it now
unfortunately the problem still exist
can you recreate it on jsfiddle or code snipped? also look for browser console error if any
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.