Creating a news zipper display using JavaScript

When used appropriately, a news zipper can give life to a web page by giving special emphasis to timely headlines. The page belows uses it to update readers on Minecon 2015 in London.

mainPage

The code relies on the JavaScript setInterval and the text substring commands.

The central part of the code is

var msgLength = 70;
var msg2 = msg + " " + msg;
var i = -1;
var zipper = function() {
if (i++ >= msg.length - 1) {
i = 0;
}
jQuery('#news_zipper').text(msg2.substr(i, msgLength));
}
setInterval(zipper, 120);

where msg is a string and msgLength is the number of characters to display as the message moves from right to left in the ‘news_zipper’ window. Characters advance every 120ms.

To center the window and fit the window to the text displayed, the following css code is used

#zipper_holder { width 100%; text-align: center; }
#news_zipper {
margin: 0 auto;
display: inline-block;
height: 20px;
padding: 10px;
box-shadow: 0 0 20px rgba(0,0,0,0.4);
background: #F2FFDF;;
}

referencing the html tags


<div id="zipper_holder"><div id="news_zipper"></div></div>

Adding code to initiate the message and hide the zipper after a specified number of completed revolutions, the complete code is




<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<style>
#zipper_holder { width 100%; text-align: center; }
#news_zipper { 
 margin: 0 auto;
 display: inline-block; 
 height: 20px; 
 padding: 10px; 
 box-shadow: 0 0 20px rgba(0,0,0,0.4); 
 background: #F2FFDF;;
}

</style>
</head>
<body>
<div id="zipper_holder"><div id="news_zipper"></div></div>
<script>

var msg = "New York Tech Journal goes to Minecon 2015, July 4 and 5 in London. Watch for updates."
var displayZipper = true;

jQuery(document).ready(function()
{
 var msgLength = 70;
 var msg2 = msg + " " + msg; 
 var i = -1; 
 var nscrolls = 0;
 var zipper = function() { 
 if (i++ >= msg.length - 1) {
 i = 0;
 if (nscrolls++ >= 1) {
 clearInterval(zipper);
 jQuery('#news_zipper').hide();
 }
 }
 jQuery('#news_zipper').text(msg2.substr(i, msgLength));
 }
 if (displayZipper) {
 setInterval(zipper, 120);
 } else {
 jQuery('#zipper_holder').hide();
 } 
});

</script>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: