Kyle
Kyle

Reputation: 11

assign variable to img src

I have a variable that I cannot edit, named reg0001, which is coming from firmware on a board that I am using. reg0001 is either a 0 or 1, and I would like to make a page that updates live, which shows a green img if reg0001 is 0, or red if it is 1. Here is what I have so far.

<div id="Oobj6"style="position:absolute;left:270px;top:60px;width:20px;height:53px;overflow:hidden;">
<input type="text" id="Gform4" class="Body-C" name="reg0001" value="%d" >
<div>
<img id="Ggeo1" src="whitelight.jpg" alt="" name="state1">
</div>

and javascript:

function updateChart() {
    var x;
    if (isIE) { // for Internet Explorer

    x = parseInt(document.getElementById("reg0001").value);
    if (x == 0) { 
        document.state1.src = "greenlight.jpg";
        }
    else {
        document.state1.src = "redlight.jpg";
    } 

right now this script works, but I have to keep refreshing the page to get the images to change, even if reg0001 changed in the background. I don't know much about javascript, I was hoping someone could point me in the right direction.

Upvotes: 1

Views: 177

Answers (3)

Govind Singh
Govind Singh

Reputation: 15490

setinterval for it

setInterval(updateChart, 5000);

it will call updateChart after each 5s
update this in your updateChart

x = parseInt(document.getElementById("reg0001").value,10);

or

x = Number(document.getElementById("reg0001").value);

to update value

document.getElementById("reg0001").value="2"

bettter way according to OP need

js

setInterval(updateChart, 5000);
var x=true;
function updateChart() {

    if (isIE) { // for Internet Explorer
    if (x) { 
        document.state1.src = "greenlight.jpg";
        x=false; 
        }
    else {
        document.state1.src = "redlight.jpg";
        x=false; 
        }
    }
}
//no need for getting any value if you just want animation 

Upvotes: 1

mplungjan
mplungjan

Reputation: 177692

I suggest you do

var tId;
window.onload=function() {
  tId = setInterval(function() {
    var x = parseInt(document.getElementById("reg0001").value,10);
    document.state1.src = x == 0?"greenlight.jpg":"redlight.jpg";
  },5000);
} 

If you do not update the field reg0001 from somewhere else, there is no point. So perhaps you need to use AJAX to get the value

Upvotes: 0

Mister Epic
Mister Epic

Reputation: 16723

You need to loop it with SetInterval:

 updateChart();
 setInterval(updateChart, 5000); //Cycles every 5 seconds

If you need to manage the cycling, you can record the interval Id that SetInterval generates:

 var intervalId = setInterval(function().... //Mindful about the scope of intervalId here!

Then later on you can stop cycling with clearInterval:

 clearInterval(intervalId);

ref: https://developer.mozilla.org/en/docs/Web/API/window.setInterval

Upvotes: 1

Related Questions