- Navigation -
Borders on mouseover

The other day someone asked me how they could make these buttons highlight when the mouse was placed over them. The way they'd done it was by making two of each image, one normal and one with a red line around the edge. It worked, but this was both heavy on bandwidth since double the images were used, and there was a slight delay the first time since it hadn't loaded the new images yet. You could eliminate the second problem by loading the images beforehand by placing them somewhere invisible, but this is still way too much work if all you want is to have a border!

The second problem is, if you turn the borders on and off, the images move. The way I told them to get around this was to have the borders on, and only change the color of it - which works, but not if you've got an image for the background.

The true answer to the problem is simple, all you need to know is that the total space around an image is made up from the borders, padding, and margin combined. By swapping values, you can achieve the effect we want, as simply as this:

<script>
function borderChange(border,padding,imgObj) {
 imgObj.style.borderWidth=border;
 imgObj.style.margin=padding;
}

</script>


<img 
   src='whatever.jpg' 
   style='border:0px solid; border-color:#FF0000; margin:5px;'
   onmouseover="borderChange('5px','0px',this);"
   onmouseout="borderChange('0px','5px',this);"
 alt=""/>

And that's it - simple. All it does is call the function to set new values of the margin and border at the right events. See the working example here.

Nearly always in Javascript the solution is simple and logical - you just need to find it. And Google is your friend.


- mitxela

© Kousou Games 2007 lowfi version
Page created in 0.0286 seconds.
Valid XHTML 1.0 Transitional Valid CSS Powered by PHP