Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I know how to use css sprites with pure html and css. But what if I dinamycally change an image by selecting a value from a dropdown box with javascript?

<select name="pricing" onchange="check_pricing();" id="pricing_value">
  <option value="">[Please Select]</option>
  <option value="Free" <?php if($pricing == 'Free'): ?> selected="selected"<?php endif; ?>>Free</option>
  <option value="Paid" <?php if($pricing == 'Paid'): ?> selected="selected"<?php endif; ?>>Paid</option>
</select>

function check_pricing() {
  var pricing = document.forms["MyForm"]["pricing_value"].value;
  if (pricing == 'Paid')
  {
    document.getElementById('table_drawad').style.backgroundImage="url('Images/drawad_bg_paid.png')";
  }
  else
  {
    document.getElementById('table_drawad').style.backgroundImage="url('Images/drawad_bg_free.png')";
  }

}

With css I would do this:

table.table_drawad{
  width:120px;
  height:123px;
  background-image:url('Images/newcampaign_sprite2.png');
  background-position:0px 0px;
}
share|improve this question
2  
Why don't you just add and remove a class.. That is lot cleaner –  Sushanth -- May 17 at 19:44
 
Also if you cache your selectors you'll make your code faster and cleaner. –  elclanrs May 17 at 19:47
 
I haven't gone into cashing yet. I am trying to optimize load times with sprites –  erdomester May 17 at 19:53
 
@Sushanth-- would you add that as a solution? It worked. Thanks. –  erdomester May 18 at 7:29

1 Answer

up vote 0 down vote accepted
    .classA{
      width:120px;
      height:123px;
      background-image:url('Images/newcampaign_sprite2.png');
      background-position:0px 0px;
    }

    .classB{
      width:160px;
      height:145px;
      background-image:url('Images/newcampaign_sprite2.png');
      background-position:0px 0px;
    }

var elem = document.getElementById('table_drawad');
if (pricing == 'Paid')
  {
    elem.className = 'classB';
  }
  else
  {
     elem.className = 'classA';
  }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.