Changing css with javascript

Hey ya’ll,

been fighting with this little problem for 3 hours or so, cannot come up with a solutions.

I simply want to change a background of a DIV with a js.

I have this CSS:


#panel2 {
  background: transparent url('../images/layout/benefits_bg21.jpg') no-repeat;
}

.panel21 {
  background: transparent url('../images/layout/benefits_bg21.jpg') no-repeat;
}

.panel22 {
  background: transparent url('../images/layout/benefits_bg22.jpg') no-repeat;
}

.panel23 {
  background: transparent url('../images/layout/benefits_bg23.jpg') no-repeat;
}

and this little javascript:


function toggleTab_uo(thisClass) {
  document.getElementById('panel2').className = thisClass;
}

and finally this html:


<div id="panel2">
 <div class="subnav tab1b_nav" id="tab1b_nav">
   <a href="javascript:toggleTab_uo('panel21');">01</a>
   <a href="javascript:toggleTab_uo('panel22';">02</a>
   <a href="javascript:toggleTab_uo('panel23');">03</a>
 </div>
..
..

and with every click on sub nav, I would like to change the background image of the Panel2 div. I tried different classes; changed colour, font size - virtually everything EXCEPT the background image; no matter what I do - the background of Panel2 stays always the same, which is the one defined for #panel2 in CSS.

What am I doin’ wrong?

Thanks for any tip or advice!
Cheers,
Greg

You have 2 issues to deal with from what I see. First you have a syntax error in your inline javascript:

 <div class="subnav tab1b_nav" id="tab1b_nav">
   <a href="javascript:toggleTab_uo('panel21');">01</a>
   <a href="javascript:toggleTab_uo('panel22';">02</a> <!--Missing closing parenthesis -->
   <a href="javascript:toggleTab_uo('panel23');">03</a>
 </div>

Secondly, your css rules are in conflict. You cannot override an ID based rule with a class based rule by default. Since both rules are active, the ID takes precedence. You have 2 options to deal with this easily. The first is to remove the rules from the ID selector into a class, and make that class active by default. The second is to use the css keyword !important to force the classes to override the id rules.
Example:

#panel2 {
  background: transparent url('../images/layout/benefits_bg21.jpg') no-repeat;
}
 
.panel21 {
  background: transparent url('../images/layout/benefits_bg21.jpg') no-repeat !important;
}
 
.panel22 {
  background: transparent url('../images/layout/benefits_bg22.jpg') no-repeat !important;
}
 
.panel23 {
  background: transparent url('../images/layout/benefits_bg23.jpg') no-repeat !important;
}

I tried the first one prior, I figured that ID has higher rank there; but the second option worked like a charm!

Thank you soo much for your time,
much appreciated!

:slight_smile:

Cheers,
Greg