Robert Stem
Robert Stem

Reputation: 43

.js alert(); when text in span change

I got this Code:

const odleglosc = parseFloat(document.getElementsByClassName("dystans")[0].innerText);

const daleko = "za daleko";

if (odleglosc > 200) {
  alert(daleko);
}
<span data-pafe-form-builder-live-preview="lechnarlok" class="dystans" id="dystans">500</span>

It runs fine, because at starting point there is number higher than 200 in it. But when i change it, alert don't trigger again..

How can i solve that? :(

Upvotes: 2

Views: 64

Answers (2)

Dawid Wekwejt
Dawid Wekwejt

Reputation: 543

Do You want to show alert after each change of the value? If yes, use event listener for input (not for span).

Update: Use MutationObserver for this case.

let span = document.getElementById('dystans');

function updateValue(value) {
  var daleko = "za daleko";
  if (parseFloat(value) > 200)
  {
     alert(daleko);
  }
}

// create a new instance of 'MutationObserver' named 'observer', 
// passing it a callback function
observer = new MutationObserver(function(mutationsList, observer) {
  let value = mutationsList.filter(x => x.target.id =='dystans')[0].target.innerHTML;
  updateValue(value);
});

// call 'observe' on that MutationObserver instance, 
// passing it the element to observe, and the options object
observer.observe(span, {characterData: true, childList: true, attributes: true});

span.innerHTML = '3000';
<span data-pafe-form-builder-live-preview="lechnarlok" class="dystans" id="dystans">500</span>

Source: Detect changes in the DOM https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Upvotes: 0

MF714
MF714

Reputation: 183

Im not sure about how the span value will change, so this example works with an input. The same idea could also be applied to a span tho.

<input onchange="theFunction()" data-pafe-form-builder-live-preview="lechnarlok" class="dystans" id="dystans" value="500"></input>

<script>

    function theFunction() {
      var odleglosc = parseFloat(document.getElementsByClassName("dystans")[0].value);
      var daleko = "za daleko";

      if (odleglosc > 200)
      {
              alert(daleko);
      }
    }

</script>

Here, onChange calls the function whenever the value in the input field changes.

Upvotes: 1

Related Questions