0

I have 5x countdown and i want to click the image below if the timer is "00:00". Now i have it like the code below but i must refresh the page everytime to click. Is there something like eventlistener for innerhtml. I solved it with timer which checks the innerhtml but i dont want to use a timer.

  var ct1 = document.querySelector("#countdown1 > span").innerText
  if (ct1 == "00:00") { document.querySelector("#farmimage_1").click(); }

  var ct2 = document.querySelector("#countdown2 > span").innerText
  if (ct2 == "00:00") { document.querySelector("#farmimage_2").click(); }

  var ct3 = document.querySelector("#countdown3 > span").innerText
  if (ct3 == "00:00") { document.querySelector("#farmimage_3").click(); }

  var ct4 = document.querySelector("#countdown4 > span").innerText
  if (ct4 == "00:00") { document.querySelector("#farmimage_4").click(); }

  var ct5 = document.querySelector("#countdown5 > span").innerText
  if (ct5 == "00:00") { document.querySelector("#farmimage_5").click(); }

5x Timer

biber54
  • 49
  • 1
  • 6
  • 2
    What? Why? Just put the listener on the span, and in the event handler for that listener, check the `event.target.textContent` (_not_ `innerHTML`, you don't care about HTML code, you care about text) – Mike 'Pomax' Kamermans May 29 '20 at 00:53
  • What do you mean by _Now i have it like the code below but i must refresh the page everytime to click_ – PolarisRouge May 29 '20 at 00:54
  • @Reggie i mean the images are only clicked only when i refresh the page – biber54 May 29 '20 at 21:19

1 Answers1

1

The MutationObserver interface can do the trick:

function toggle() {
  let div = document.getElementById('d0');
  div.textContent = div.textContent == 'foo'? 'bar':'foo';
}

window.onload = function(){

  document.getElementById('b0').addEventListener('click', toggle, false);
  
  let div = document.getElementById('d0');
  let observer = new MutationObserver(function() {
    console.log('textContent changed to ' + div.textContent);
  });
  observer.observe(div, {childList: true});

}
<div id="d0">foo</div>
<button id="b0">Toggle foo/bar</button>

Using with a timer:

// Simple countdown
function timer(){
  let div = document.getElementById('timer');
  let time = div.textContent;
  let intervalID = setInterval(() => {
    div.textContent = --time;
    if (time == 0) clearInterval(intervalID);
  }, 1000);
}


window.onload = function() {

  // Create observer
  let div = document.getElementById('timer');
  let observer = new MutationObserver(function() {
    if (div.textContent == '0') {
      console.log('Zero!!');
    }
  });
  // Start observing
  observer.observe(div, {
    childList: true
  });
  // Start timer
  timer();
};
<div id="timer">5</div>
RobG
  • 142,382
  • 31
  • 172
  • 209