Button //JavaScript Repository

Description

Transforms an image into a button, allows setting images for the following mouse events: over, out, click and release.
Created: 2005.10.02 - Modified 2005.10.03

Dependencies

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/dhtml/button [rev. #1]

Button = function(id){
    var o = this;
    o.ini = (o.b = document.images[id]).src;
    o.i = {}, o.over = o.out = o.click = o.release = null;
};
Button.prototype.checkImage = function(i){
    return !(i.fileSize == -1 || !i.width);
};
Button.prototype.init = function(){
    var o = this, b = o.b;
    o.out && ((o.i.o = new Image()).src = o.out);
    addEvent(b, "mouseout", function(){
        b.src = !o.out ? o.ini : o.checkImage(o.i.o) ? o.out : b.src;
    });
    if(o.over){
        (o.i.h = new Image()).src = o.over;
        addEvent(b, "mouseover", function(){
            o.checkImage(o.i.h) && (b.src = o.over);
        });
    }
    if(o.click){
        (o.i.c = new Image()).src = o.click;
        addEvent(b, "mousedown", function(){
            o.checkImage(o.i.c) && (b.src = o.click);
        });
    }
    if(o.release || o.click){
        o.release && ((o.i.r = new Image()).src = o.release);
        addEvent(b, "mouseup", function(){
            var c = o.i.r || o.i.h || o.i.o;
            b.src = c && o.checkImage(c) ? c.src : o.ini;
        });
    }
};

Example (Example)

<img src="http://www.google.com.br/images/logo_sm.gif" style="border:1px solid #f00;" id="imagem1" alt="imagem" /><br />Over
<hr /><img src="http://www.google.com.br/images/logo_sm.gif" style="border:1px solid #0f0;" id="imagem2" alt="imagem" /><br />Click
<hr /><img src="http://www.google.com.br/images/logo_sm.gif" style="border:1px solid #00f;" id="imagem3" alt="imagem" /><br />Out
<hr /><img src="http://www.google.com.br/images/logo_sm.gif" style="border:1px solid #f0f;" id="imagem4" alt="imagem" /><br />Release

<script type="text/javascript">
//<![CDATA[

var j, i, img = ["imagem1", "imagem2", "imagem3", "imagem4"],
    s = "http://www.google.com.br/intl/pt-BR_br/images/logo.gif";
for(j = img.length; j--;){
    i = new Button(img[j]);
    if(j == 0) i.over = s;
    else if(j == 1) i.click = s;
    else if(j == 2) i.out = s;
    else i.release = s;
    i.init();
}

//]]>
</script>

Help

Constructor

Button(Id: String)
Generates an instance of Button
Id
Id of the image that will be used as button.

Properties

Button.over: String
Path of the image that will be shown when the mouse is over.
Button.click: String
Path of the image that will be shown after clicking.
Button.release: String
Path of the image that will be shown after releasing the mouse.
Button.out: String
Path of the image that will be shown when the mouse is out.

Adjust just the properties that you need, the not setted properties will be ignored.

Rank (Votes: 39)

2.05