Swiper destroy не работает

destroy() not working #671

Comments

rodrigomorais commented Mar 10, 2014

First of all, congratulations for this amazing plugin!

Now the sad part:
I am working on a project which has a block with a swiper only on mobile version and a common list on desktop version. I was trying to use destroy on JS resize event but it says that «object has no method destroy». If a put a «data-swiper» on my HTML and try «mySwiper.data(‘swiper’).destroy()», it says «Cannot read property ‘h’ of null».

What should be done?

The text was updated successfully, but these errors were encountered:

nolimits4web commented Mar 11, 2014

Can you please show your full JS code regarding Swiper? destroy works, but probably you call it in a wrong way

rodrigomorais commented Mar 11, 2014

var mySlider = $(‘.container’);
if($(window).outerWidth()

nolimits4web commented Mar 11, 2014

I see now. This line is correct: mySlider.data(‘swiper’).destroy();. But there is a problem, resize event triggers continuously during resize, and after «destroy» swiper removes variable stored in mySlider.data(‘swiper’). So you should use it like:

rodrigomorais commented Mar 11, 2014

it still returns the error «Cannot read property ‘h’ of null». I thought that once the destroy is activated, it would return errors on console, but even with them the swiper would be destroyed, but this just does not happen

nolimits4web commented Mar 11, 2014

Need to see live example then, because according to JS everything should work

rodrigomorais commented Mar 12, 2014

I used some of your demos for testing by the way. Thank you

nolimits4web commented Mar 13, 2014

rodrigomorais commented Mar 13, 2014

Nice. It works now. I am not sure if it would be usefull but when the swiper is destroyed, the inline style remains, so I had to do a $(‘.swiper-slide, .slide-wrapper’).attr(‘style’, »); to make the layout become as it was before. Maybe adding this functionality on your plugin?

Читайте также:  Керхер поломоечная машина не работает

Thank you very much, and congratulations once again for your work.

nolimits4web commented Mar 13, 2014

No, this functionality will not be added, because it is not always required, only in some cases like yours. So yes, if you need it, you can just reset styles by clearing «style» attribute

iLoyola commented Mar 26, 2014

This functionality would help me right now, I hope you reconsider.

Источник

Почему не убираются стили и стрелки Swiper при destroy?

Почему не убираются стили и стрелки Swiper при destroy?
Нужно, чтобы слайдер работал только при вьюпорте >1000, а при меньшем была кучка картинок.
Вроде бы написано mySwiper.destroy( true, true ) — должны убраться. А они остаются.

  • Вопрос задан 25 нояб. 2020
  • 292 просмотра

Про стили не понял, а стрелки. Встречный вопрос — почему они должны убираться? Вы эти элементы создали — сами и решайте, что с ними делать. Например, можно их показывать/прятать при создании/уничтожении слайдера. После инициализации/дестроя у контейнера переключается класс swiper-container-initialized , можно назначать нужные стили в зависимости от его наличия:

Встречный вопрос — почему они должны убираться?

mySwiper.destroy(deleteInstance, cleanStyles); Destroy slider instance and detach all events listeners, where
deleteInstance — boolean — Set it to false (by default it is true) to not to delete Swiper instance
cleanStyles — boolean — Set it to true (by default it is true) and all custom styles will be removed from slides, wrapper and container. Useful if you need to destroy Swiper and to init again with new options or in different direction

И еще нашла пример, в котором работает https://codepen.io/aaronkahlhamer/pen/GveaXP?edito.
только там media в другую сторону.
А у меня нет 🙁

Потому что так написано в документации

Да ну? Не вижу тут ни слова про удаление элементов. Про удаление обработчиков событий — есть. Про вырезание стилей — есть. Про удаление элементов — нет.

нашла пример, в котором работает

Источник

Откуда возникает ошибка со слайдером?

Добрый день, подскажите в чем проблема. Есть слайдер, нужно, чтобы он отрабатывал с одними параметрами до 857 и дальше вместо листания появлялся эффект фейд. Через брейкпоинты такое не сделать. Надо дестрой делать слайдера и заново его инициализировать. С первой частью справился. Он на заданном разрешении деактивируется. Но не могу сделать, чтобы на определенном разрешении он снова активировался. Пишет в девтулс ошибку Uncaught TypeError: Cannot read property ‘destroy’ of undefined.

  • Вопрос задан 14 янв.
  • 271 просмотр

Destroy slider instance and detach all events listeners, where
deleteInstance — boolean — Set it to false (by default it is true) to not to delete Swiper instance
cleanStyles — boolean — Set it to true (by default it is true) and all custom styles will be removed from slides, wrapper and container. Useful if you need to destroy Swiper and to init again with new options or in different direction

Передайте false в метод destroy.

Читайте также:  Как настроить роутер innbox e80 ростелеком

И как предложение: а что если не делать destroy, а в зависимости от размеров окна браузера делать init с разными настройками?

cupacabka, у вас код как-то награмождён.
Вам нужна 1 функция, которую нужно вызвать при загрузке документа и при ресайзе.
Скажем,

Ну и, возможно, в функции инициализации слайдера, перед вызовом new Swiper, нужно будет проверить есть ли свойство destroy в swiperSlider и если если, вызвать его.

Источник

Почему не убираются стили и стрелки Swiper при destroy?

Почему не убираются стили и стрелки Swiper при destroy?
Нужно, чтобы слайдер работал только при вьюпорте >1000, а при меньшем была кучка картинок.
Вроде бы написано mySwiper.destroy( true, true ) — должны убраться. А они остаются.

  • Вопрос задан 25 нояб. 2020
  • 292 просмотра

Про стили не понял, а стрелки. Встречный вопрос — почему они должны убираться? Вы эти элементы создали — сами и решайте, что с ними делать. Например, можно их показывать/прятать при создании/уничтожении слайдера. После инициализации/дестроя у контейнера переключается класс swiper-container-initialized , можно назначать нужные стили в зависимости от его наличия:

Встречный вопрос — почему они должны убираться?

mySwiper.destroy(deleteInstance, cleanStyles); Destroy slider instance and detach all events listeners, where
deleteInstance — boolean — Set it to false (by default it is true) to not to delete Swiper instance
cleanStyles — boolean — Set it to true (by default it is true) and all custom styles will be removed from slides, wrapper and container. Useful if you need to destroy Swiper and to init again with new options or in different direction

И еще нашла пример, в котором работает https://codepen.io/aaronkahlhamer/pen/GveaXP?edito.
только там media в другую сторону.
А у меня нет 🙁

Потому что так написано в документации

Да ну? Не вижу тут ни слова про удаление элементов. Про удаление обработчиков событий — есть. Про вырезание стилей — есть. Про удаление элементов — нет.

нашла пример, в котором работает

Источник

destroy iDangerous Swiper if window is resized to a bigger resolution or call it when resized to a smaller resolution

i’m using iDangerous Swiper for my website in lower resolutions. here is how i’m calling it:

so, when you access it in a desktop browser, the swiper will not be called. what i want to do is to «turn it on» if the user resizes the window to a size smaller than resolution or destroy it if the user accesses it in a small window size and then resizes it to bigger than resolution . i tried this, but it didn’t work:

Читайте также:  Как настроить умную розетку feron

two undesirable things happen:

  1. if the user is in a small resolution and resizes it to a resolution that still calls the swiper, it restarts the swiper.
  2. if the user is in a small resolution and resizes it to a bigger resolution, it is not destroyed.

i thing my problem is the typeof . i don’t know much how variables work when they are called like this: $(‘.swiper-container’).swiper() .

how do i «uncall» swiper and how not call it if it was already called?

6 Answers 6

I was having the same problem and found that as soon as the width was beyond my max width, mySwiper was again undefined and therefore the if(typeof) statement always returned false .

I found another hybrid solution with the fired[] array below and also realized that while the destroy() method may be executing in my example, the swiper itself had added a style attribute to the wrapper and slide DIVs which was persisting after the destroy method was called and only went away with a page refresh. After I added the removeAttr() method calls on the two DIVs, everything worked as expected.

Your mileage may vary.

I had the same problem and took a similar solution:

init function:

my resize function:

For anyone still having problems destroying and initialising Swiper on demand try calling reInit() with a slight delay.

define Swiper reference on page load

If your updating markup through ajax ensure you empty the container first. i.e:

Okay, so I know I’m late to the party, but I had similar issues and ended up with a solution that works solid.

The story: Swiper needs to run on desktop, but not on mobile (small screens) and should be able to change between them on resize.

Requirements: In my example, I’m using jQuery, Swiper and Modernizr (for media queries, as window width etc is unreliable).

JavaScript:

As well as checking the ‘device’ (in other words, mobile size or desktop size), it checks against a flag I set in state.swiper . As this is a mobile-first approach, this flag is initially set to false .

I know that my explanation is brief, but this works 100% and has the benefit of not initializing Swiper at every stage of the resize, thanks to the flag.

The HTML would just be the standard HTML that Swiper requires, so that’s what you should use if you’re going with this solution.

Источник

Оцените статью