lundi 27 juillet 2020

Why does this if/else script not work in HTML/Javascript

I don't know much about coding, javascript or HTML and put my HTML together in Dreamweaver mostly by using Google and CMD+C / CMD+V. This script below is not working the way I want it to, so can someone that actually understand coding please have a look at it and see why it is not working as intended?

<script>
var url = 'NowPlaying.txt';
var storedText;

function nprefresh() {
  fetch(url)
    .then(function(response) {
      response.text().then(function(text) {
        storedText = text;
        currentSong();
      });
    });
}

setInterval(nprefresh, 10000);

var npinfo = storedText.length; 
var nomusic = "Information currently not available (No Music)"

function currentSong() {
  if (npinfo < 1) {
    document.getElementById("thesong").textContent = nomusic;}
else if (npinfo > 112) {
    document.getElementById("thesong2").textContent = storedText;}
else {
    document.getElementById("thesong").textContent = storedText;
    }
}
</script>

The expected behavior is supposed to be like this:

The Fetch part gets "Now Playing" song information from my text file (that part works).

Then, if the txtfile is empty (the if < 1) it should displayed the static "Information not available" part. However if the text exceeds a certain amount of characters (the else if > 112) it should put the 'storedText' into the "thesong2" div, which is actually an animated marquee in my HTML. If both conditions are not met (the last else statement) it should just put the storedText into a non animated div.

This last part actually works! I can see in my HTML that the fetched text always gets put into the non-animated div and is displayed.

So my assumtion is, that the error is somewhere in the length check and the script doesn't perform it as intended? Seems to just jump to the last else (But then again I don't know about coding and could be completely wrong)

Thanks in advance for any help! Kind regards Sabrina

Aucun commentaire:

Enregistrer un commentaire