Ever wanted to have an old-school stock ticker on your website, like the kind you see at the bottom of certain news programs? Maybe for a financial blog, or a personalized search portal? If you have had this need, but don’t have much programming experience, you have probably run into a few problems. The easy way of using a pre-made java or flash applet is near impossible, as free ones are difficult to find, and they still require that you have the quote data stored locally on the server that will be hosting the ticker. To do that, you’d need a system of retrieving quote data and storing it on your server – but if you could do that, you probably wouldn’t need the java/flash applet, as you could just include the stock data in your page using super simple PHP or CGI, and then scroll it with a HTML marquee tag.

ATTN:
The data source that this script was using for stock data is no longer working. I have yet to get around to fixing the problem. You will need to modify this script to get data via another method.

<rant>Whoops, except that some elitist snobs in a secret standards committee decided marquee shouldn’t exist in any HTML or CSS standard. They figured that with all the terrible web designers out there abusing marquee on their page headers and giving poor netizens headaches from trying to follow the darn things, there must not be any legitimate use for the tag. Therefore, they took up the quest to eliminate marquee from the web altogether. And, if you ask on most web developer forums about how to get a marquee on your page, you’ll get nine replies criticizing you for wanting one (without asking why) for every one attempt at a helpful answer, which probably wasn’t helpful at all.</rant> *Ahem*. So. Yes. The point is, if you use a marquee tag, it won’t validate and won’t work universally. It’s supposedly coming up in CSS3, but if you don’t want to wait, your only option is Javascript.

Now, if you look for some quick handy-dandy Javascript marquee scrollers on Google, you’ll probably run into three types: super-complicated ones that take a ton of code or require external files, scripts that scroll vertically instead of horizontally, or ones that predefine the content within the script and don’t let you gracefully insert HTML.

So here, I will solve these problems for you by (A) providing you with a simple PHP script to gather stock data into useful HTML, and (B) a simple Javascript marquee that will work on a div with any content. And if the client has Javascript disabled, it will display the content anyway without scrolling.

If done right, it will look something like this:

Javascript Marquee

First, let’s get the marquee script working, since everything else goes inside it. Stick this CSS code into your stylesheet, or directly between the CSS style tags in the head of your HTML document:

#marqueeborder {
	color: #cccccc;
	background-color: #000000;
	font-family:"Lucida Console", Monaco, monospace;
	position:relative;
	height:20px; 
	overflow:hidden;
	font-size: 0.7em;
}
#marqueecontent {
	position:absolute;
	left:0px;
	line-height:20px;
	white-space:nowrap;
}

 

Leave the positioning, spacing, and wrapping parts alone for now. You can change colors and fonts to your liking. Matching “line-height” to the div height is a cheap way of vertically centering a single line of text, and you can modify or delete both values if you like. Everything else is critical to the scroller script. It’s safe to add a width specification to #marqueeborder.

Put this javascript code somewhere on your page above the relevant content. The script can be put directly above the #marquee divs.

<script type="text/javascript">
	// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com

	// Set an initial scroll speed. This equates to the number of pixels shifted per tick
	var scrollspeed=2;
	var pxptick=scrollspeed;
	function startmarquee(){
		// Make a shortcut referencing our div with the content we want to scroll
		marqueediv=document.getElementById("marqueecontent");
		// Get the total width of our available scroll area
		marqueewidth=document.getElementById("marqueeborder").offsetWidth;
		// Get the width of the content we want to scroll
		contentwidth=marqueediv.offsetWidth;
		// Start the ticker at 50 milliseconds per tick, adjust this to suit your preferences
		// Be warned, setting this lower has heavy impact on client-side CPU usage. Be gentle.
		setInterval("scrollmarquee()",50);
	}
	function scrollmarquee(){
		// Check position of the div, then shift it left by the set amount of pixels.
		if (parseInt(marqueediv.style.left)>(contentwidth*(-1)))
			marqueediv.style.left=parseInt(marqueediv.style.left)-pxptick+"px";
		// If it's at the end, move it back to the right.
		else
			marqueediv.style.left=parseInt(marqueewidth)+"px";
	}
	window.onload=startmarquee;
</script>

Permission is hereby given to use, modify, or redistribute the above code in any form or fashion for any purpose, private or commercial, so long as the credit comment is left intact.

 

Without the comments, this script is only 15 lines of code. Neat, huh? Edit the scroll speed and interval to your liking, as indicated by the comments.

Now, the HTML code:

<div id="marqueeborder" onmouseover="pxptick=0" onmouseout="pxptick=scrollspeed">
<div id="marqueecontent">

<?-- Content goes here! -->

</div>
</div>

 

Everything inside the #marqueecontent div will be scrolled, and it doesn’t matter if the contents are wider than #marqueeborder. Mousing over the thing will temporarily pause it. If Javascript is disabled client-side, the contents will just sit there (and be partially hidden if they’re too big) without scrolling.

You can edit this script to make it scroll vertically just by altering some of the parameters. If I get enough requests, I may make an article about it.

Now, for the stock data.

PHP Stock data

First of all, you are going to need to create a cache directory. Name it “stockcache” and put it in the same directory as the document that will call this PHP script. Make it writable by the web server, which means to chmod it to 755, 775, or as a last resort, 777. (A more secure option would be to use ACLs if your webhost supports it)

Now, insert this PHP code into the #marqueecontent div:

<?php

	// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com

	// List your stocks here, separated by commas, no spaces, in the order you want them displayed:
	$stocks = "idt,iye,mill,pwer,spy,f,msft,x,sbux,sne,ge,dow,t";

	// Function to copy a stock quote CSV from Yahoo to the local cache. CSV contains symbol, price, and change
	function upsfile($stock) { copy("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1c1&e=.csv","stockcache/".$stock.".csv"); }

	foreach ( explode(",", $stocks) as $stock ) {

		// Where the stock quote info file should be...
		$local_file = "stockcache/".$stock.".csv";

		// ...if it exists. If not, download it.
		if (!file_exists($local_file)) { upsfile($stock); }
		// Else,If it's out-of-date by 15 mins (900 seconds) or more, update it.
		elseif (filemtime($local_file) <= (time() - 900)) { upsfile($stock); }

		// Open the file, load our values into an array...
		$local_file = fopen ("stockcache/".$stock.".csv","r");
		$stock_info = fgetcsv ($local_file, 1000, ",");

		// ...format, and output them. I made the symbols into links to Yahoo's stock pages.
		echo "<span class=\"stockbox\"><a href=\"http://finance.yahoo.com/q?s=".$stock_info[0]."\">".$stock_info[0]."</a> ".sprintf("%.2f",$stock_info[1])." <span style=\"";
		// Green prices for up, red for down
		if ($stock_info[2]>=0) { echo "color: #009900;\">&uarr;";	}
		elseif ($stock_info[2]<0) { echo "color: #ff0000;\">&darr;"; }
		echo sprintf("%.2f",abs($stock_info[2]))."</span></span>\n";
		// Done!
		fclose($local_file); 
	}
?>
<span class="stockbox" style="font-size:0.6em">Quotes from <a href="http://finance.yahoo.com/">Yahoo Finance</a></span>

Permission is hereby given to use, modify, or redistribute the above code in any form or fashion for any purpose, private or commercial, so long as the credit comment is left intact.

 

Only 14 lines of code. The only thing you should have to edit is the $stocks variable to reflect your preferences. To be courteous, if you edit this script, please leave the Yahoo Finance links intact, to benefit the fine company which so graciously lets us leech this content from their servers.

Basically, when a user visits your site, the script will display the specified quotes from Yahoo Finance. But this would be a problem with a high-traffic site, as you’d be hammering Yahoo’s servers with multiple requests with every visit, wasting everyone’s precious time and bandwidth. Therefore, this script will save information to the “stockcache” directory, and only download new quotes if the existing data is 15 minutes or older. I highly recommend, if you have or develop the ability, that you modify this script to also account for times when the market is closed.

Meanwhile, to finish up, let’s dress the output a bit with CSS:

.stockbox {
	margin:0 10px;
}
.stockbox a {
	color: #cccccc;
	text-decoration : underline;
}

 

Here is a list of some sites using this script. Contact me to have your site added.

Alright, here ends another installment of my tech blog. Enjoy!

 

UPDATE 12MAR2014: If you are using WordPress, you will need to put the “stockcache” directory in your root. If you want it elsewhere, add a line to the top of the PHP code which defines its location:

        chdir('/path/to/wordpress_root/livedemos/stockticker');