Cory Cory - 1 year ago 80
Javascript Question

Javascript reading .txt file and displaying in HTML

I'm trying to have JavaScript on my HTML page read from a .txt file (status.txt) in the same directory and display the contents in two different font colors based on the information in the .txt file. I currently have it displaying the text on the page just fine, but I wanted to make it a bit more noticeable. Here is my current code to display the text with the basic #ccc hex.

<script type="text/javascript">
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("status").innerHTML = xmlhttp.responseText;
}"GET", "status.txt", true);

<h3 id="status" style="padding-right: 7px; padding-left: 7px; margin-top: 2px; font-size: 11px; color: #cccccc">

The text file contents are overwritten every time a .vbs file is ran. It will either say:

6/11/2016 8:58:30 AM Script Started


6/11/2016 9:31:12 AM Script Stopped

The only thing that changes is the timestamp. I would like the text to display as red when it says "(timestamp) Script Stopped" and green when it says "timestamp) Script Started". If anyone could help, that'd be great!

Answer Source
var color = xmlhttp.responseText.indexOf('Started') !== -1 ? 'green' : 'red';
document.getElementById("status").innerHTML = '<span style="color: ' + color + '">' + xmlhttp.responseText + '</span>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download