jQuery – How to Create a News Ticker with just a few JavaScript lines?

As you already know now, I love to reinvent the wheel ( jQuery always allows me that), and because of that, once more, we’ll see how to create something which already exists: a news ticker.

Usually the “news ticker” is a display of news which scroll horizontally, like those which can be seen in some newscasts in the lower part of the screen. Our news ticker will be slightly different given that the news won’t scroll horizontally but vertically instead, and in between the news there will be a pre-established pause (I think that this method gives prominence to every single news and at the same time it gives more time to the reader to read the article at hand, but obviously this is only my opinion).

We’ll be using jQuery for creating the News Ticker which allows us with only a few code lines (eleven in our case) to obtain outstanding effects, which consume few resources and give the extra touch to our website.
Thanks to this simple article you will learn how to create a News Ticker, like the one visible here. All we need is (X)HTML, CSS and a little bit of jQuery.

Providing the necessary stuff

The first thing to do is prepare a html document on which to work on: what we need is really not much, since the animation per se is really simple.

Let’s see the following (X)HTML markup used to obtain the desired effect:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>jQuery News Ticker - Your Inspiration Web</title>

	<script type="text/javascript" src="./script/jquery-1.4.min.js"></script>
	<script type="text/javascript" src="./script/common.js"></script>

	<link rel="stylesheet" href="./style/screen.css" type="text/css" media="all" />
</head>
<body>
	<div id="wrap">
		<div id="head" class="block"></div>

		<div id="content">
			<div id="info" class="block">
				<ul id="ticker">

					<li>
						<span>Title Lorem Ipsum 1</span>
						<a href="#">
							Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec suscipit, ante id porttitor faucibus, odio
							eros pellentesque sapien, at consectetur mi nibh at massa.
						</a>
					</li>

					<li>
						<span>Title Lorem Ipsum 2</span>
						<a href="#">
							Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec suscipit, ante id porttitor faucibus, odio
							eros pellentesque sapien, at consectetur mi nibh at massa.
						</a>
					</li>

					<li>
						<span>Titlr Lorem Ipsum 3</span>
						<a href="#">
							Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec suscipit, ante id porttitor faucibus, odio
							eros pellentesque sapien, at consectetur mi nibh at massa.
						</a>
					</li>

					<li>
						<span>Title Lorem Ipsum 4</span>
						<a href="#">
							Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec suscipit, ante id porttitor faucibus, odio
							eros pellentesque sapien, at consectetur mi nibh at massa.
						</a>
					</li>

					<li>
						<span>Title Lorem Ipsum 5</span>
						<a href="#">
							Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec suscipit, ante id porttitor faucibus, odio
							eros pellentesque sapien, at consectetur mi nibh at massa.
						</a>
					</li>

				</ul>
			</div>
		</div>

	</div>

</body>
</html>

First of all, we obviously have to include the jQuery library, downloadable by clicking here, and an external file (in our case named “common.js“) in which we are going to insert the script for the functioning of the news ticker.

What’s essential for our script is a disarranged list of elements: the ul/li structure.
To sum up it’s about a series of news, “locked” inside a “cage”, which allows the display of a maximum of “N” news at a time.

Taking as an example the proposed code, let’s see which are the characteristics that our list should have.

The ul, which has “ticker” as an id, must have a fixed height which corresponds to the height of every li multiplied by the number of elements to display: if for example, the height of every li is 100 px and I want to display only two, then the height of ul will be 200px (100×2) and so on.
In our case, the height of the ul corresponds to the height of every li, since we are going to display one at max, in order to highlight every single news.
In addition to defining a height, it is extremely important that our ul has the overflow property set on hidden, in such a way that all the content which exceeds the defined height is not displayed.

Let’s see below the CSS code used for the formatting of our news list.

ul#ticker {
	width: 220px;
	height: 120px;
	overflow: hidden;
}

ul#ticker  li {
	width: 200px;
	height: 99px;
	padding: 10px;
	border-bottom: 1px dashed #ccc;
}

ul#ticker li a {
	color: #666;
}

ul#ticker li span {
	display: block;
	color: #06C;
}

As you can see, setting the structure of the ticker is very simple, in this example we have applied also a small edge and a padding to all lis, but everybody is free to personalize the news list the way they think its best, because as we mentioned, the most important part regards to the formatting of ul.

Once our structure is ready, we can move on to the most entertaining part: JavaScript.

How to create the script to make the News Ticker function?

Our script has to be a simple function which every tot seconds removes the first news from the list, and re-inserts it in last position; in order to render everything more attractive, we will move the first news with an upper negative margin, in such a way that it shifts towards the top and thus is no longer displayed (thanks to the overflow property:hidden applied to the ul), and as a consequence the second news is going to replace the first automatically.

Below you can find the code with which we will put into practice what was mentioned above:

$(function()
{
	var ticker = function()
	{
		setTimeout(function(){
			$('#ticker li:first').animate( {marginTop: '-120px'}, 800, function()
			{
				$(this).detach().appendTo('ul#ticker').removeAttr('style');
			});
			ticker();
		}, 4000);
	};
	ticker();
});

We start to grasp the meaning.

A new function is defined and the nametickeris assigned to it; all its contents will be executed after X seconds (4 in this case), in order to do that, we will make use of the setTimeout() timer, to which as a first subject we pass the code to execute, and as second the quantity of ms (milliseconds) after which to execute it.

Inside the ticker function we select the first which is found inside of “#ticker, or the element which has “ticker” as an id (our ul); in order to do that, the selector we use is the following: $(‘#ticker li:first’).

Once obtained the element, we have to move it towards the top in such a way that the following element takes its place,  in order to do that we have to animate it until it reaches, as upper margin value of -120px (margin-top: -120px), that is to saythe height of every single li.

In order to obtain the effect we just described, we apply to the element the animate() method, and as an animation parameter, we use the upper margin (marginTop) which is going to have as value the height of every li (in our case 120px) in negative, in such a way that it moves towards the top (marginTop: ‘-120px’); the length of the animation is passed as second parameter of animate(), and in this case it is of 800ms.

The third parameter to be passed to animate() represents our callback, that is, the function which will be called when the animation will be ready.
See the magic happen: through the detach() method of jQuery, we remove from the DOM the selected li, but we keep the element in memory, so we can reuse it.

At this point, we use the appendTo() method, to “hang” the element to a new selector (our ul), and finally we apply the removeAttr() method, which deals with removing from the element, the attribute passed as an argument (style, in this case), otherwise the element would be reinserted with the last properties applied by the animation, that is margin-top: -120px.

Immediately after the application of the animate() method to our element, the function “calls” itself, in a such a way that to repeat the operation again after 4 seconds.

Note: if your javascript file is called inside the tag head, it is important to insert our script inside the ready() method of jQuery, in such a way that it is launched to the loading of DOM, in our case we do it through the following code:

$(function()
{
	// code to  execute
});

as seen, it is the compact version of:

$(document).ready(function()
{
	// code to execute
});

Conclusions

Once again, jQuery makes our life a lot easier; in fact thanks to only 12 lines of JavaScript, we were able to create a small comfortable News Ticker.
This time reinventing the wheel wasn’t that difficult… what do you think ?

download
Versione: 1.0
Pubblicato: 27 June 2010
Dimensione: 26.59 kB
Download: NewsTicker

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: , ,

The Author

Nicolas is a web programmer with a passion for web design and javascript. He spends most of his free time looking for new ideas and new projects to be developed. It Wordress and jQuery fanatic and has fun in creating plugins for the latter.

Other articles written by

Related Posts

You may be interested in the following articles:

30 comments

  1. duc
  2. duc
  3. Alfred
    • Nicolas
  4. Theo
  5. Jinx
  6. drbyers
  7. narender
  8. lushr
  9. Friv

Trackback e pingback

  1. Tweets that mention jQuery – How to Create a News Ticker with just a few JavaScript lines? | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by V. Tavares (E-Goi). V. Tavares (E-Goi) said: jQuery – How to Create …
  2. Tweets that mention jQuery – How to Create a News Ticker with just a few JavaScript lines? | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by Franco Averta. Franco Averta said: RT@YIW #jQuery – How to Create a …
  3. SmashinGeeks Design News–Tutorials, RoundUps and Freebies {June} — SmashinGeeks - Blogging | Designs | Tutorials | Graphics | Wordpress | Blogging | Tech News | Downloads
    [...] to Create a News Ticker with just a few JavaScript. This tutorial is also available for Download. Read Full …
  4. Element with jquery |Avnish Namdev
    [...] [ 14 Comments ] [...]
  5. Some HTML,CSS usefull Links | funneyzone
    [...] http://www.yourinspirationweb.com/en/jquery-how-to-create-a-news-ticker-with-just-a-few-javascript-l... [...]

Leave a Reply

Current day month ye@r *