TechScribe Notes

일정 너비 이상에서만 슬라이드 작동하도록 하기 본문

project/jquery

일정 너비 이상에서만 슬라이드 작동하도록 하기

yunmee0704 2024. 11. 26. 16:44
	// 241025 QA반영
			function initializeSwipers() {
				const deviceWidth = $(window).width();
				const thresholdWidth = deviceWidth - 40;

				$('.district__swiper').each(function () {
					let totalSlidesWidth = 0;

					$(this).find('.swiper-slide').each(function () {
						const slideWidth = $(this).outerWidth(true); // margin 포함한 넓이
						totalSlidesWidth += slideWidth;
					});

					// 기존 스와이퍼가 있다면 파괴
					if ($(this).data('swiper')) {
						$(this).data('swiper').destroy(true, true);
					}

					// 조건을 만족할 경우에만 스와이퍼 초기화
					if (totalSlidesWidth > thresholdWidth) {
						const swiper = new Swiper(this, {
							slidesPerView: "auto",
							paceBetween: 8,
							grabCursor: true,
						});

						// 스와이퍼 인스턴스를 데이터 속성에 저장
						$(this).data('swiper', swiper);
					}
				});
			}

			// 초기화 함수 호출
			initializeSwipers();

			// 윈도우 리사이즈 이벤트에 핸들러 추가
			$(window).on('resize', function () {
				initializeSwipers();
			});

		});