Showing posts with label tip. Show all posts
Showing posts with label tip. Show all posts

Sunday, May 8, 2011

JavaScript rollover images

Here is a quick tutorial to show you a function to make JavaScript rollovers.

The function

var devc = {
            rollover: function (id, img1, img2) {
                this.addEvent(id, 'mouseover', function () {
                    $(id).src = img2;
                });
                this.addEvent(id, 'mouseout', function () {
                    $(id).src = img1;
                });
            },
            addEvent: function (id, _event, _function) {
                _object = $(id);
                if (_object.addEventListener) {
                    _object.addEventListener(_event, _function, false);
                } else if (_object.attachEvent) {
                    if (_event.length > 2) {
                        if (_event.substring(0, 2) != "on") {
                            _event = 'on' + _event;
                        }
                    }
                    _object.attachEvent(_event, _function);
                }
            }
        };

I added the addEvent function from our previous post for convenience; however, you can see the original post from the link in the resource section of this post.
The rollover function simply adds two functions to the onmouseover and onmouseout events. The JavaScript on mouse over assigns image 2 to the image object and onmouseout adds image 1 to the image object.


Usage:

JavaScript

window.onload = function () {
            devc.rollover('roll', 'star.png', 'starover.png');
        };

HTML

<img id='roll' src="star.png" />