No jQuery: creating a news ticker with JavaScript and CSS

No jQuery: creating a news ticker with JavaScript and CSS

A pure JavaScript and CSS news ticker.

CSS transitions work on a well-defined set of properties. The interesting thing of transitions is that they work also when a CSS property is changed via JavaScript by means of the style object. Here is a practical example of how this feature works.

We want to build a news ticker that scrolls vertically with a specific time interval. Our news ticker features ten items but only the first five items are initially visible.

The CSS code is similar to many other news ticker implementations:


#ticker {
	width: 180px;
	height: 400px;
	margin: 2em auto;
}

#ticker-wrapper {
	height: 100%;
	width: 100%;
	overflow: hidden;
	position: relative;
	
}

#ticker-wrapper ul {
	margin: 0;
	padding: 0;
	list-style: none;
	width: 100%;
	height: 800px;
	position: relative;
	transition: all 1500ms ease-in;
}

#ticker-wrapper li {
	display: block;
	height: 80px;
	width: 100%;
	margin-bottom: 0.3em;
	position: relative;
}

We've set the transition property on the innermost container. Our container will be moved upwards with a negative value of its top property.

The first thing we need to do is to attach to each item its corresponding offset value which will be later used with the top property:


_setElementOffsets: function() {
	var self = this;
	var li = self.items;

	for( var i = 0; i < self.totalItems; ++i ) {
		var item = li[i];
		var top = item.offsetTop;

		item.setAttribute( "data-top", top );
	}
}

Using the offsetTop property works well in this case because each item has been relatively positioned. Now we can create the ticking mechanism by using a JavaScript timer:


tick: function() {
	var self = this;
	self._setElementOffsets();

	self.timer = setInterval(function() {
		self.index++;

		if( self.index == self.totalItems ) {
			self.index = 0;
		}

		var item = self.items[self.index];
		var top = item.getAttribute( "data-top" );
		self.wrapper.style.top = "-" + top + "px";


	}, 1500 );
}

Using an incremental index allows us to select the current item, get its offset value and move upwards our wrapper. As you can see, the time interval is equal to the interval specified in the transition declaration, that is, 1500 milliseconds.

As a final touch, we can pause our timer when we hover an item with the mouse and resume the scrolling movement on mouseout.


hover: function() {
	var self = this;
	var li = self.items;

	for( var i = 0; i < self.totalItems; ++i ) {
		var item = li[i];
		item.addEventListener( "mouseover", function() {
			clearInterval( self.timer );
			self.timer = null;

		}, false);
		item.addEventListener( "mouseout", function() {
			self.tick();

		}, false);
	}	
}

[view-example url="http://codepen.io/gabrieleromanato/pen/IoDBy"]