0

I have a DHT sensor and I used mqtt to send data to server. From there I displayed the data to a span, so the span value is changing.

What I want to do is:
When sensor stop working, it will display fault in that span and I want to display image only when its fault.

<span id="fault"></span>

i tried to use JS to get the span then display image but its not working

<img src="yellowled.png" alt="Girl in a jacket" width="60" height="60" id="my_image">
    
<script>
    document.getElementById('my_image').style.display = 'none';
    var span_Text = document.getElementById("fault").innerText;
    if (span_Text  === "fault"){
       document.getElementById('my_image').style.display = 'inline';
    }
</script>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
qarn.ooz
  • 29
  • 1
  • 7
  • for me, your code is correct, when `fault` it shows the image, as expected – Calvin Nunes Nov 06 '20 at 12:37
  • i tried that but the results shows empty string cause the sensor fault take some time to send the data – qarn.ooz Nov 06 '20 at 12:39
  • 1
    ah, then your problem is not what you think it is, you are not waiting the response, this is your problem. When sending data and waiting for response you need to await – Calvin Nunes Nov 06 '20 at 12:40
  • Related: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Calvin Nunes Nov 06 '20 at 12:41
  • 1
    Where is the code that puts the fault message into the span? That's where you need to set the image to visible. –  Nov 06 '20 at 12:46

2 Answers2

1

If your span value is changing without refreshing the page, You need to trigger function on change value of span.

for that you need to make function:

function functionName(){
var span_Text = document.getElementById("fault").innerText;
    if (span_Text  === "fault"){
       document.getElementById('my_image').style.display = 'inline';
    }
}

Then you need to set Javascript MutationObserver on your span id as onchange will not work for span.

Then you need to call your function when DOM changes.

var yourSpan = document.getElementById("fault");
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.info('changed');
    functionName();
  });    
});
 
var setting = { attributes: true, childList: true, characterData: true };
 
observer.observe(yourSpan, setting);
Claymore
  • 130
  • 4
1

Use a MutationObserver

function callback (event) {
    // inspect event or event.target.textContent and react
}
observer = new MutationObserver((events) => events.forEach(callback));
observer.observe(document.getElementById("fault"), {childList: true, subtree: true, characterData: true});
netizen
  • 1,028
  • 7
  • 19