Skip to content

Instantly share code, notes, and snippets.

@robbyrussell
Created January 29, 2009 06:02
Show Gist options
  • Select an option

  • Save robbyrussell/54404 to your computer and use it in GitHub Desktop.

Select an option

Save robbyrussell/54404 to your computer and use it in GitHub Desktop.
basic carousel-like class using Prototype
<div id="x_container">
<a id="x_back_button"><img src="/images/left-arrow.png" /></a>
<a id="x_forward_button"><img src="/images/right-arrow.png" /></a>
<div class="x_widget">
<p>content...1</p>
</div>
<div class="x_widget" style="display:none;">
<p>content...2</p>
</div>
<div class="x_widget" style="display:none;">
<p>content...3</p>
</div>
</div>
<script type="text/javascript">
new ElementSlider( 'x_container', '.x_widget', 'x_back_button', 'x_forward_button' );
</script>
var ElementSlider = Class.create();
ElementSlider.prototype = {
initialize: function( container_element, item_element, back_button_element, forward_button_element ) {
this.container_element = container_element;
this.items = $( this.container_element ).select( item_element ).toArray();
this.back_button_element = back_button_element;
this.forward_button_element = forward_button_element;
this.current_item_index = 0;
this.observeBackButton();
this.observeForwardButton();
},
observeBackButton: function() {
Event.observe( this.back_button_element, 'click', this.moveBack.bindAsEventListener(this), false );
},
observeForwardButton: function() {
Event.observe( this.forward_button_element, 'click', this.moveForward.bindAsEventListener(this), false );
},
moveForward: function() {
if ( this.items[this.current_item_index] == this.items.last() ) {
this.current_item_index = 0;
} else {
this.current_item_index += 1;
}
this.resetItems();
},
moveBack: function() {
// if first, set to last
if ( this.items[this.current_item_index] == this.items.first() ) {
this.current_item_index = ( this.items.size() - 1 );
} else {
this.current_item_index = ( this.current_item_index - 1 );
}
this.resetItems();
},
resetItems: function() {
this.items.each( function( item ) { $( item ).hide(); })
this.items[this.current_item_index].show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment