Skip to content

Instantly share code, notes, and snippets.

@navitronic
Created September 17, 2013 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navitronic/6588564 to your computer and use it in GitHub Desktop.
Save navitronic/6588564 to your computer and use it in GitHub Desktop.
Channel selector
SF.channel_selector = {
init: function($channel_selector) {
var self = this;
if ($channel_selector.length > 0) {
self.channel_selector = $channel_selector.addClass('selector');
self.channel_tabs = self.channel_selector.find('.channel-tabs a');
self.channel_strip = self.channel_selector.find('.channel-strip');
self.channel_strip.css('width', (self.channel_tabs.length * 100) + '%' );
self.tab_width = Math.round(self.channel_selector.width() / self.channel_tabs.length);
self.count = 0;
self.width_left = 834;
self.channel_strip.html('');
self.channel_tabs.each(function(){
self.count++;
if (self.count < self.channel_tabs.length) {
$(this).width(self.tab_width - 2);
self.width_left -= self.tab_width;
} else {
$(this).width(self.width_left);
}
self.channel_strip.append(self.generate_channel($(this)));
});
self.channel_tabs.on('click', function(e){
e.preventDefault();
clearInterval(self.interval);
self.channel_tabs.removeClass('active');
($.proxy(self.animate, self, $(this).index()))();
$(this).addClass('active');
}).eq(0).trigger('click');
self.channel_tabs.fadeIn();
self.interval = setInterval(function(){ self.switch_channel(1); }, 5000);
// Bind arrow keys to channel selector.
$(document).on('keyup', $.proxy(function (e) {
clearInterval(this.interval);
if (e.keyCode === 37) {
this.prev_channel();
}
if (e.keyCode === 39) {
this.next_channel();
}
}, self));
}
},
// Generates the html for displaying the image. should match the html in serverside template.
generate_channel: function($channel_tab) {
var c = $('<div class="channel"/>'), a = $('<a/>').attr('href', $channel_tab.attr('href'));
a.append($('<img width="834" height="420"/>').attr('src', $channel_tab.data('image-url')));
c.append(a);
return c;
},
next_channel: function() {
return this.switch_channel(1);
},
prev_channel: function() {
return this.switch_channel(-1);
},
switch_channel: function(factor) {
var self = this;
factor = typeof factor === 'undefined' ? 1 : factor;
var active = self.channel_tabs.filter('.active'),
new_index = active.index() + factor,
new_tab = self.channel_tabs.eq(new_index);
if (new_tab.length === 0) {
new_index = 0;
new_tab = self.channel_tabs.eq(new_index);
}
if (new_tab.length > 0 && new_index > -1) {
active.removeClass('active');
new_tab.addClass('active');
self.animate(new_index);
}
},
animate: function(index) {
var self = this;
self.channel_strip.css('left', index * -100 + '%');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment