Dave
Dave

Reputation: 15

JavaScript - Change class when if/ elseif condition is fulfilled

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.

Upvotes: 0

Views: 373

Answers (1)

epascarello
epascarello

Reputation: 207501

If the code has run already, you need to remove the classes that you have added. client.onreadystatechange = function checktxt() {

With your code, you can just call

boxgreen.classList.remove("red");  //or green for the other case

and than it will work.

Or you can use toggle and simplify the code so you do not have the same lines over and over again.

client.onreadystatechange = function() {

  var isValid = client.responseText == 'not' || client.responseText == 'younger',
      text = isValid ? "Connect is working" : "Connect isn't working!",
      box = document.querySelector("#response");

  box.innerHTML = text;
  box.classList.toggle("green", isValid);
  box.classList.toggle("red", !isValid);

}

Upvotes: 1

Related Questions