Use a slideshow with a teardown()
or destroy()
method that is able to remove any elements and event listeners it created.
Any jQuery plugin using the jQuery UI widget factory will have this but unfortunately many others do not. You could try this carousel https://github.com/richardscarrott/jquery-ui-carousel, just be sure to include jQuery widget factory: http://jqueryui.com/widget/
Secondly do not attempt to sniff whether or not the device is mobile, don't be stuck thinking in terms of devices. What if the user wants to view the carousel on their phone? What if their device is wrongly interpreted to be mobile? Making assumptions may come back to bite you. Detecting features and properties is safer and should be more future-friendly.
Think about the problem you are trying to solve, if it is "this slideshow would work better if presented as a list on small viewports" then go ahead and check the size of the window or test a media query with matchMedia()
before instantiating the plugin (why do all the work just to undo it again) and again if the viewport resizes or device orientation changes.
In plain JS (and for a relatively up-to-date browser) that might be something like:
var slideshowControl = function(element, breakpoint) {
var api;
var initSlideshow = function() {
api = new Slideshow(element);
};
var removeSlideshow = function() {
api.teardown();
api = undefined;
};
// Test media query
return function() {
// Test if match media is available
var matchMedia = window.matchMedia || window.msMatchMedia;
if ( ! matchMedia) {
return;
}
if (matchMedia('all and (max-width:' + breakpoint + ')').matches && ! api) {
return initSlideshow();
}
if (matchMedia('all and (min-width:' + breakpoint + ')').matches && api) {
return removeSlideshow();
}
};
}(document.querySelector('.slideshow'), 640);
window.addEventListener('resize', slideshowControl);
window.addEventListener('DOMContentLoaded', slideshowControl);