Skip to content

onResize() uses swiper.slides.length instead of virtual slides count, causing incorrect slideTo in Virtual mode #8162

@shawn-mnoko

Description

@shawn-mnoko

Check that this is really a bug

  • I confirm

Reproduction link

https://codesandbox.io/p/sandbox/wt9n47

Bug description

In onResize() (swiper-core.mjs), when Virtual mode is enabled with slidesPerView > 1, the function uses
swiper.slides.length (rendered DOM element count) instead of the virtual slides array length. This causes an
incorrect slideTo call that jumps to the wrong slide position.

The same file's update() method already handles this correctly by checking swiper.virtual.slides:

// update() - CORRECT (line 3634-3636)
const slides = swiper.virtual && params.virtual.enabled ? swiper.virtual.slides : swiper.slides;
translated = swiper.slideTo(slides.length - 1, 0, false, true);

// onResize() - BUG (line 2703-2704)
swiper.slideTo(swiper.slides.length - 1, 0, false, true);
// swiper.slides.length = ~4 (DOM elements), not ~10 (virtual slides)

Reproduction

1. Create a Swiper with Virtual mode enabled, ~10 slides, slidesPerView: 2, slidesPerGroup: 2
2. Navigate to the last slide (e.g., slide index 8)
3. Trigger a container resize (e.g., by resize window)
4. Expected: Swiper stays at the last slide
5. Actual: Swiper jumps to slide index 2-3

Root cause

onResize() enters this branch when slidesPerView > 1 and swiper.isEnd === true:

if ((params.slidesPerView === 'auto' || params.slidesPerView > 1)
    && swiper.isEnd && !swiper.isBeginning
    && !swiper.params.centeredSlides && !isVirtualLoop) {
  swiper.slideTo(swiper.slides.length - 1, 0, false, true);
  //             ^^^^^^^^^^^^^^^^^^^^^^
  //             DOM elements (~4), NOT virtual slides (~10)
}

In Virtual mode, swiper.slides contains only the currently rendered DOM elements (typically 4-6), while the
actual slide count is in swiper.virtual.slides. This makes slideTo(3) navigate to the beginning instead of
staying at the end.

### Expected Behavior

_No response_

### Actual Behavior

_No response_

### Swiper version

v12.1.2

### Platform/Target and Browser Versions

chrome

### Validations

- [x] Follow our [Code of Conduct](https://github.com/nolimits4web/swiper/blob/master/CODE_OF_CONDUCT.md)
- [x] Read the [docs](https://swiperjs.com/swiper-api).
- [x] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
- [x] Make sure this is a Swiper issue and not a framework-specific issue

### Would you like to open a PR for this bug?

- [x] I'm willing to open a PR

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions