null_byte null_byte - 1 year ago 69
Javascript Question

Javascript, change css background image when colour changes

i made this script for my forum and i was wondering if someone could help me out, when the color changes to red, i want the background image to be:

/images/redshield.png


and on green

/images/greenshield.png


here is the script

function flashy(index) {
setTimeout(function() {
if (index > 1) {
index = 0;
for (x = 0; x < document.getElementsByClassName('style113').length; x++) {
document.getElementsByClassName('style113')[x].style.color = 'Lime';
}
} else {
for (x = 0; x < document.getElementsByClassName('style113').length; x++) {
document.getElementsByClassName('style113')[x].style.color = 'Red';
}
}
index++;
flashy(index);
}, 100);
}

Answer Source

It really depends on what is the element you want to change the background image for, but guessing it is the same elements that get the color attribute, then:

function flashy(index){
 setTimeout(function(){
  if(index > 1){
   index = 0;for(x = 0; x <            document.getElementsByClassName('style113').length; x++){
    document.getElementsByClassName('style113')[x].style.color = 'Lime';
    document.getElementsByClassName('style113')[x].style.backgroundImage = "url('/images/greenshield.png')";
   }
  }else{
   for(x = 0; x < document.getElementsByClassName('style113').length; x++){
    document.getElementsByClassName('style113')[x].style.color = 'Red';
    document.getElementsByClassName('style113')[x].style.backgroundImage = "url('/images/redshield.png')";
    }
  }index++;flashy(index);
 }, 100);
}