I decided to refactor the code for a responsive image gallery, that I setup not too long ago. Following the suggestions @joseph-the-dreamer made, and some other best practices, I cut down on the number of if statements.
Is there anything else I could do to make the activateSlider function more concise?
Is there another method one could use (in general) to avoid having to keep calling the same function on resize?
/* jQuery throttle / debounce - v1.1 - 3/7/2010 */
function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}}
function activateSlider() {
var slider = $('#slider'),
sliderContainer = $('.orbit-container'),
sliderContainerLinks = $(sliderContainer).children('a'),
sliderKids = $('#slider li'),
sliderContent = $('.slider-content'),
sliderKidsContent = $(sliderKids).children(sliderContent),
inactiveKidsContent = $('#slider li:not(.active) .slider-content'),
accordionContainer = $('.accordion-container'),
sliderBulletsContainer = $('.orbit-bullets-container');
function transformSlider() {
$(slider).foundation({
orbit: {
slide_number: false,
timer: true,
timer_speed: 8000,
next_on_click: false
}
});
if(window.matchMedia("(max-width: 767px)").matches) {
/* Disable orbit gallery styles */
$(sliderContainer).after($('.orbit-timer'));
$(slider, sliderKids).attr('style', '');
$(slider).removeClass('orbit-slides-container').removeAttr('data-orbit').addClass('accordion-container');
$(sliderKids).removeAttr('data-orbit-slide').removeClass('active');
$(sliderContainerLinks, sliderKidsContent).hide();
$(inactiveKidsContent).css('display', 'none');
/* Init accordion click functions */
$(sliderKids).unbind().bind('click', function(){
$(this).toggleClass('active').siblings().removeAttr('class');
$(this).siblings().find(sliderContent).slideUp();
$(this).find(sliderContent).slideToggle();
});
} else {
/* If accordion styles are present, remove them */
var OrbitStyles = ($(accordionContainer).length === 0);
if (!OrbitStyles) {
$(sliderContainerLinks).show();
$(slider).removeClass('accordion-container').addClass('orbit-slides-container').attr('data-orbit', '');
$(sliderBulletsContainer).before($('.orbit-timer'));
$('.orbit-timer').removeClass('paused');
}
$(sliderContent).show();
$(sliderKids).first().addClass('active').siblings().removeAttr('class');
}
}
transformSlider();
}
$(function(){
if (window.Foundation) {
activateSlider();
}
});
/* Call the script on resize (must support ie8) */
if (window.addEventListener) {
window.addEventListener('resize', debounce(function () {
activateSlider();
}, 250));
} else {
window.attachEvent('resize', debounce(function () {
activateSlider();
}, 250));
}
EDIT: It looks a little crude (stylewise) but the working version is here: http://jsbin.com/gicin/14/