Too much to type for every image: Code maintainability suffers
A couple of things bothered me about this code:
- You need to give the image a unique ID ('sub_but') and then need to refer to that ID in the anchor tag code. So, you need to type the name of the ID multiple times. And since the image is directly enclosed by the anchor tag, it is also annoying to have to do that. It seems like there should be a better way.
- You also need to spell out the image names in three different locations. Once in the image tag ('moveup.gif') and twice in the anchor tag ('movedown.gif' and 'moveup.gif' again).
Using a function doesn't really help much in this case: I still need to refer to the image ID and filenames just as often as before.
The solution: Inspecting the DOM tree
I wanted to change this. I didn't want to have to type image IDs and image names multiple times. I didn't want the surrounding anchor tag to have attributes that carefully and accurately need to refer to something contained within it (the image tag).
How does it work? Well, the imageRoll() function takes this as an argument, a reference to the surrounding object, in this case that is the anchor tag object. It then finds the first image object that is enclosed by the anchor tag. It extracts the filename from that image object. From that, it changes the name of the image source to either refer to the special hover image, or vice versa, as needed. Thus, the button image changes.
Other related posts:
Apple demonstrates: With great marketing even the crappiest product can be sold
Comment by stuartm, on 27-Apr-2009 20:25
Comment by Cd-MaN, on 28-Apr-2009 01:03
A simpler way to do this (without any JS at all) would be to use the :hover CSS pseudo-selector. However it might have issues with older browsers like IE 6.
Comment by Ragnor, on 28-Apr-2009 10:32
Use CSS and an image spirte, eg:
Comment by Alexander Mikhalev, on 1-May-2009 01:21
Use a:hover, to set up such behaviour for all links.