Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Forked from eric1234/marquee.coffee
Created August 25, 2010 20:27
Show Gist options
  • Save walterdavis/550226 to your computer and use it in GitHub Desktop.
Save walterdavis/550226 to your computer and use it in GitHub Desktop.
var Marquee = Class.create({
initialize: function(element) {
this.element = $(element);
this.paused = false;
// If everything fits don't bother with all this mess
if(this.element.scrollWidth == this.element.clientWidth) return;
// Defaults to scrolling through all content in 40 seconds.
// There is a limit to how fast we can go since we move by a pixel
// at a time (for smooth scrolling) and most browsers can only call
// our callback so fast even if we tell it to go faster.
var duration = element.getAttribute('data-duration') || 40;
// Create wrapping container to scroll the marquee in. Move
// some of the relevant marquee styles to this wrapper.
this.container = this.element.wrap('div');
this.container.setStyle({
width: this.element.clientWidth+'px',
height: this.element.clientHeight+'px',
overflow: 'hidden'
});
// Keep in mind how big it was so we know when to reset
this.originalWidth = this.element.scrollWidth;
// Make it look like it is wrapping around by duping content
this.element.innerHTML += this.element.innerHTML;
// Record the movement necessary before we reset to the start
this.resetWidth = this.element.scrollWidth - this.originalWidth;
// Size restrictions/clipping moved to wrapper, remove from element
this.element.setStyle({
width: this.element.scrollWidth+'px',
height: this.element.scrollHeight+'px',
overflow: 'auto'
});
// Calculate how often to move and setup timer
var frequency = duration/this.element.getWidth();
frequency = (100*frequency).round() / 100;
new PeriodicalExecuter(this.move.bind(this), frequency);
// Setup events to pause animation if moused over
this.element.observe('mouseover', this.pause.bind(this));
this.element.observe('mouseout', this.play.bind(this));
},
move: function() {
if(this.paused) return; // Don't scroll if paused
// If we have scrolled all content reset back to the start
if(this.container.scrollLeft == this.resetWidth)
this.container.scrollLeft = 0;
// Scroll just by a pixel
this.container.scrollLeft += 1;
},
pause: function() {this.paused = true},
play: function() {this.paused = false}
});
// Anything with class "marquee" should be scrolled
Event.observe(window, 'load', function() {
$$('.marquee').each(function(e) {new Marquee(e)})
})
<!DOCTYPE html>
<html>
<head>
<style>
.marquee {
font-size: 3em;
width: 10em;
height: 1.5em;
overflow: hidden;
white-space: nowrap;
}
</style>
</head>
<div class="marquee">
The quick brown fox jumps over the lazy dog
</div>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
<script src="/javascripts/marquee.js"></script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment