0

I am recieving measurements _date and _time from a device on regular intervals. When measurements arrive, I update the innerHTML of an element using:

document.getElementById("t_001").innerHTML = `${_date}, ${_time}`;

and element with ID t_001 is changing it's value fine. Now I want to create a nice fade in fade out animation (using opacity) for the text whenever inner.HTML is updated.


In order to do this I want to manipulate CSS of the element through a function animation() like this:

let x = document.getElementById("t_001");

x.addEventListener("change", animation());

function animation(){
    // CSS Changes will take place here but this is never triggered...
    console.log(x);
}

But the function never triggers... How come?

71GA
  • 1,132
  • 6
  • 36
  • 69
  • 4
    There is no `change` event for `innerHTML`, only for `value` on form elements like `input`, `textarea`. What you need is a `MutationObserver`. Aside from that, your approach is more than questionable. Instead of the listener, make the code that changes the `innerHTML` apply a CSS class that results in the animation you need. – connexo Jun 20 '20 at 19:17
  • So what could I do here? I probably have to change the 1st chunk of code as well... – 71GA Jun 20 '20 at 19:18
  • 1
    You can follow this article. https://stackoverflow.com/questions/50683026/input-addeventlistener-on-change-not-firing. Hope it will help. – Shivanshu Gupta Jun 20 '20 at 19:23

1 Answers1

0

As others pointed out, change will not be triggered when the HTML of your element changes. But, seeing as the animation code needs to be in a different JS file and both files have access to the t_001 element, you should be able to trigger a custom event from the first file when new data is received and detect it in the second.

File 1

let x = document.getElementById("t_001");
let e = new Event('customEvent');

x.innerHTML = `${_date}, ${_time}`;
x.dispatchEvent(e);

File 2

let x = document.getElementById("t_001");

x.addEventListener("customEvent", animation());

function animation() {
    console.log(x);
}
AJ_
  • 1,455
  • 8
  • 10