Thursday 6 September 2007

Element.setAttribute and other strange problems

Heed this.

If you're using javascript events like onmouseover and onmouseout, don't bother using them if you want to do something clever.

My plan for these events was as follows:
  • Your image has an onmouseover and onmouseout state. An on / off state.
  • When clicking this image, the onmouseover and onmouseout state change. So does the source of the image.
The trouble with this is that if you want to modify the onmouseover and onmouseout events dynamically in a javascript function depending on whether the image has been clicked or not, you're out of luck. Firefox supports the element.setAttribute('attribute','property') method, but Internet Explorer versions do not.

Even what Firefox does support seems to be patchy, and doesn't complete my image swapping. The event states didn't want to stick across browser versions.

It turns out that if you want to alter those mouse-related events, you can't do it dynamically in a javascript function. IE won't let you at all, and Firefox's support seems to be buggy.

So how did I get around this?

Our creative girl produced a cascading stylesheet which had images with on/off states in them, and then moved the image depending on what the class of the div surrounding our image was. From there, we could alter the class of the div and therefore alter the hover states.

For example:




Where price_result1 in the stylesheet is:

.price_result1 {
width:44px;
height:12px;
background:url(../images/result_headers/price.gif);
float:left;
}

.price_result1 a {
display:block;
width:44px;
height:12px;
background:url(../images/result_headers/price.gif) 0% 0% no-repeat;
}
.price_result1 a:hover {background-position:0% 75%;}

price_result2 is:

.price_result2 {
width:44px;
height:12px;
background:url(../images/result_headers/price.gif) 0% 75% no-repeat;
float:left;
}
.price_result2 a {
display:block;
width:44px;
height:12px;
background:url(../images/result_headers/price.gif) 0% 75% no-repeat;
}
.price_result2 a:hover {background-position:0% 100%;}





And so on.

I hope this helps. Really I do, because it took me three days to work this out.

No comments: