English English

Display lines from an external text file into an unordered HTML list

This is a Javascript code which allows you to display every line of an external text file (will be fetched from an URL) in an unordered <ul> HTML list. You can use this to display, for example, news headlines on this jQuery news ticker that is available on Github:

https://github.com/sburtenshaw/Responsive-Ticker

You can also create or use any other newsticker that uses <ul> to display text.

In line 3 enter the URL of your txt file that you would like to use:

function loadNewsFromNewsfile(){
	var request = new XMLHttpRequest();
	request.open('GET', 'https://WEBSEITE/MY_TEXTFILE.txt', true);
	request.send(null);
	request.onreadystatechange = function() {
		if (request.readyState === 4 && request.status === 200) {
			var type = request.getResponseHeader('Content-Type');
			//check if a txt file was loaded
			if (type.indexOf("text") !== 1) {
				//save file into an object array with all file lines
				txtfileLines = (request.responseText).split('\n');
				
				//create content from txt file for news ticker plugin
				document.getElementById('newsticker-content').innerHTML = '<ul>';
				var textline = "";
				for(int i=0; i<txtfileLines.length; i++){
					document.getElementById('newsticker-content').innerHTML += '<div>';
					textline = "<li style=\"font-weight: bold\"><span>" + txtfileLines[i] + "</span></li>";
					document.getElementById('newsticker-content').innerHTML += textline;
					document.getElementById('newsticker-content').innerHTML += '/<div>';					
				}
				document.getElementById('newsticker-content').innerHTML += '</ul>';
			}
		}
	}
}​

This code reads an external text file through a GET request and saves every line in an object array. Then every line will be displayed through an unordered list item.

Run this function every hour:

setInterval(loadNewsFromNewsfile, 1000 * 60 * 60);



Important: You have to set an exception (whitelist) in your CORS (Cross-Origin Request) settings (of your web server) for the website that you want to fetch your text file from. If you use Apache2 it will look like this:

Header set Access-Control-Allow-Origin "*"​

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.

Ok