Twitist Forums
How can I create several javascript image buttons? - Printable Version

+- Twitist Forums (http://twitist.com)
+-- Forum: Other forums (/forum-31.html)
+--- Forum: General Internet related Qustions (/forum-32.html)
+--- Thread: How can I create several javascript image buttons? (/thread-154456.html)



How can I create several javascript image buttons? - 266 - 05-08-2014 05:41 PM

Hi,
I am new at creating websites in html. I use free for all SeaMonkey software. So, I want to create several image buttons which would change when user moves the mouse over the image. I already have created 3 images for the different stages of each button (normal, active and clicked). I wrote this code for first button:

<body>
<a href="first.html" onmouseover="return changeImage(jsbutton)"
onmouseout="return changeImageBack(jsbutton)">
<img name="jsbutton" src="first normal.png" alt="first">
<script type="text/javascript">
function changeImage()
{
document.images["jsbutton"].src= "first active.png";
return true;
}
function changeImageBack()
{
document.images["jsbutton"].src = "first normal.png";
return true;
}
</script> </a>
</body>


And It works. But when I did the same for second button it didn't worked and in addition first one has stopped to work too. So, what I have to change to make it work properly?


- Chris - 05-08-2014 05:44 PM

First of all, it doesn't work because you're overriding the functions of the first button.

Secondly, this way of doing it is about 20 years old and should have died a deserved and overdue death a long, long time ago.

More importantly though, using images for buttons, especially if the button text is part of the image, is a really bad idea, because every little change forces you to recreate all the images.
CSS3 can do gradients, shadows, borders, custom fonts, whatever you want. You can create very stylish buttons using just text, and changing them is as easy as changing a few words in your code.

Still, if you need to do this with images, you need to use the CSS sprites method.
The idea is to set the image as background-image for your <a> element instead of using a separate <img>, but make it bigger than the actual button and also contain the hover image. On hovering, the background-image is repositioned to show the hover part.
The advantages: no JavaScript necessary, and you won't have to preload the onhover image to avoid there being a delay with slow internet connections.

Here's example code:
http://jsfiddle.net/khrismuc/qYd9M/