Sineth Sineth - 16 days ago 5
Ajax Question

Arduino and JS/Cpp

I have a project "smart house" and I use Arduino Mega with Ethernet Shield. My problem is connect data from arduino to GUI website (I am beginner in JS).
When I press the button, the data is sent to Arduino and my button change color from red to green (light on) -> This is ok.

Then, if I open the door i would like to div color change from red to green and i dont know how..

This is Arduino code:

int count; // used by 'for' loops
int sw_arr[] = {30,31,32,33,34,35}; // pins interfaced to switches

for (count = 0; count < 5; count++) {
cl.print("<switch>");
if (digitalRead(sw_arr[count])) {;
cl.print("OFF");
}
else {
cl.print("ON");
}
cl.println("</switch>");
}


On my website the string change from OFF to ON, but i would like to background color change and i think that my problem is Javascript.

This is orginal code from tutorial:

var count;
var num_an = this.responseXML.getElementsByTagName('switch').length;

for (count = 0; count < num_an; count++) {
document.getElementsByClassName("doors")[count].innerHTML =
this.responseXML.getElementsByTagName('switch')[count].childNodes[0].nodeValue;
}


I change this code, but still not working:

var count;
var num_an = this.responseXML.getElementsByTagName('switch').length;

for (count = 0; count < num_an; count++) {

if(this.responseXML.getElementsByTagName('switch')[count].childNodes[0].nodeValue === "ON") {
$('.doors').css('background', '#989898');
}
else {
$('.doors').css('background', '#FA6900');
}

}


HTML Code:

<div class="item-door light-red doors">
<div id = "door">
<i class="fa fa-key"></i>
<p>Door</p>
</div>
</div>


So summary, I need change DIV background color from red to green instead string ON/OFF.

If someone have a time and could help me I would be very thankful!

Answer

The code $('.doors').css('background', '#989898'); changes the background of all container which contains the class "doors". In you for statement, if the last iteration changes background for #FA6900, all your div will get the #FA6900 color.

If you want to change only one container you have to write :

$( $(".doors").get(count) ).css('background', '#989898').`

There is two time $() because .get() return a DOM element and not a jquery element so we need to transform it again if we want to apply the .css() method.

Last point : #989898 is grey and #FA6900 is orange

Comments