I'd like some tips on optimizing the following code.
I'm a bit concerned that I'm 'polluting the global namespace' by not wrapping it in a function. The commented out var rotator { init {
came from a JavaScript tutorial but I'm not sure it's the jQuery way? Should I wrap it in $(function()
... instead?
$(document).ready(function() {
//Promos rotation
var $accordionList = $('.accordion').find('li');
// var rotator = {
// init: function() {
var numberOfItems = $accordionList.length;
var currentItem = 0;
// Set first item to active
$accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800, function() {});
var infiniateLoop = setInterval(function() {
if(currentItem == numberOfItems - 1){
currentItem = 0;
}
else {
currentItem++;
}
// Remove active class, if is has it, and close content
$accordionList.parent().find('li.active').removeClass('active')
.find('.content').slideToggle(800, function() {
});
// Add active class and open content
$accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800, function() {
});
}, 4000 );
//$('.accordion li').on('click', function () {
$accordionList.on('click', function () {
// Stop rotation
clearInterval(infiniateLoop);
var $accordionHead = $(this);
// Remove active class, if is has it, and close content
$accordionHead.parent().find('li.active').removeClass('active')
.find('.content').slideToggle(800, function() {
});
// Add active class and open content
$accordionHead.addClass('active').find('.content').slideToggle(800, function() {
});
});
// }
// };
// rotator.init();
});
$(function(){}) === $(document).ready(function(){})
\$\endgroup\$$(document.ready(function
... \$\endgroup\$$(document).ready
. The addition or removal of therotator
object does not change this fact. Either way it's wholey contained within afunction
\$\endgroup\$var
keyword you are surely not polluting the global namespace \$\endgroup\$