I'm working on a script which reads a text file and changes the text in an div depending on the content of the .txt file.
But that isn't my Problem. I don't want just plain text, the background color should change depending on which condition of the if/elseif/else function is fulfilled.
var client = new XMLHttpRequest();
client.open('GET', 'text.txt');
client.onreadystatechange = function checktxt() {
if(client.responseText =='not')
{
document.getElementById("response").innerHTML="Connect is working";
var boxgreen = document.querySelector("#response");
boxgreen.classList.add("green");
}
else if (client.responseText =='younger')
{
document.getElementById("response").innerHTML="Connect is working";
var boxgreen = document.querySelector("#response");
boxgreen.classList.add("green");
}
else
{
document.getElementById("response").innerHTML="Connect isn't working!";
var boxred = document.querySelector("#response");
boxred.classList.add("red");
}
}
client.send();
.green {
width: 140px;
height: 140px;
background: #68B267;
color: white;
}
.red {
width: 140px;
height: 140px;
background: #ec4f3e;
color: white;
}
<div id="response"></div>
My first try was to add a "classList.add" to the if/ else function, but even if the "if" condition is fulfilled it changes the class to "red" because it has been set at last.
I'm pretty new to javascript and have no experience with ajax or jquery but maybe that's what I'm looking for.