Tithos Tithos - 5 months ago 10
jQuery Question

Conditionally Change BG image jQuery

I need to conditionally change the background of div based on the value of a variable here is my code:

<script type="text/javascript">
$(document).ready(function(){
if (combo.hcs <= 10) && (combo.hcs >= 1)
$(".myClass").css("background-image", "url('BB.png')";
else if (combo.hcs <= 20) && (combo.hcs >= 11)
$(".myClass").css("background-image", "url('BH.png')";
else if (combo.hcs <= 30) && (combo.hcs >= 21)
$(".myClass").css("background-image", "url('BM.png')";
else if (combo.hcs <= 40) && (combo.hcs >= 31)
$(".myClass").css("background-image", "url('HB.png')";
else if (combo.hcs <= 50) && (combo.hcs >= 41)
$(".myClass").css("background-image", "url('HH.png')";
else if (combo.hcs <= 60) && (combo.hcs >= 51)
$(".myClass").css("background-image", "url('HM.png')";
else if (combo.hcs <= 70) && (combo.hcs >= 61)
$(".myClass").css("background-image", "url('MB.pmg')";
else if (combo.hcs <= 80) && (combo.hcs >= 71)
$(".myClass").css("background-image", "url('MH.png')";
else if (combo.hcs <= 99) && (combo.hcs >= 81)
$(".myClass").css("background-image", "url('MM.png')";
}
</script>


I am not sure if this is the best approach or not but ether way, I am getting the following error in Chrome:

Uncaught SyntaxError: Unexpected token &&

Answer

You need to include your two conditions inside the same brackets, like this :

else if (combo.hcs <= 99 && combo.hcs >= 81)

The complete corrected code :

<script type="text/javascript">
  $(document).ready(function(){
    if (combo.hcs <= 10 && combo.hcs >= 1)
      $(".myClass").css("background-image", "url('BB.png')");
    else if (combo.hcs <= 20 && combo.hcs >= 11)
      $(".myClass").css("background-image", "url('BH.png')");
    else if (combo.hcs <= 30 && combo.hcs >= 21)
      $(".myClass").css("background-image", "url('BM.png')");
    else if (combo.hcs <= 40 && combo.hcs >= 31)
      $(".myClass").css("background-image", "url('HB.png')");
    else if (combo.hcs <= 50 && combo.hcs >= 41)
      $(".myClass").css("background-image", "url('HH.png')");
    else if (combo.hcs <= 60 && combo.hcs >= 51)
      $(".myClass").css("background-image", "url('HM.png')");
    else if (combo.hcs <= 70 && combo.hcs >= 61)
      $(".myClass").css("background-image", "url('MB.pmg')");
    else if (combo.hcs <= 80 && combo.hcs >= 71)
      $(".myClass").css("background-image", "url('MH.png')");
    else if (combo.hcs <= 99 && combo.hcs >= 81)
      $(".myClass").css("background-image", "url('MM.png')");
  }
</script>