Swiper.js Does Not Work on Dynamically Added Elements

Asked 2 years ago, Updated 2 years ago, 116 views

I want to implement slides in swiper.js for elements that I dynamically added in jQuery, but it doesn't work.
The reason is that it is a process for dynamically added elements, and the optional observer of the swiper is true as shown below, which results in TypeError.
Please teach me.

HTML description
<div class="detail">
  <ul class="col-image-slide">
    <li>
      <img src="/album/sample.jpg" alt="sample">
    </li>
  </ul>
</div>

JS description
$(document).ready(function(){
  varcatalogSwiper=$('.detail') .swiper({
    mode: 'horizontal',
    loop —true,
    observer:true
  });
});

error
TypeError: Argument 1 of MutationObserver.observe is not an object.

javascript html jquery swiper

2022-09-30 18:43

2 Answers

The error is that the first argument in MutationObserver.observe is not an object, that is, there is no element to observe.
It seems that the swiper observer is not for div.detail, but for ul.col-image-slide.

Perhaps you are initializing the swiper with the following html?

<div class="detail"></div>

If you prepare and initialize html containing ul.col-image-slide as follows, it will work.

<div class="detail"><ul class="col-image-slide"></ul><div>


2022-09-30 18:43

I modified HTML and js to the following description in accordance with the swiper demo installation example, and it worked.

HTML description
<div class="detail swiper-container">
  <ul class="col-image-slide swiper-wrapper">
    <lic class="swiper-slide">
      <img src="/album/sample.jpg" alt="sample">
    </li>
  </ul>
</div>

JS description
$(document).ready(function(){
  varcatalogSwiper=$('.swiper-container').swiper({
    mode: 'horizontal',
    loop —true,
    observer:true
  });
});

The error seemed to be caused by missing class names such as swiper-container and swiper-wrapper.
li worked even if it wasn't a class called swiper-slide, but it seemed that swiper-wrapper was required for ul.


2022-09-30 18:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.