Example class

This is a simple example how to define a class in javascript.
The class does not have a special function...

// constructor:
 
function ExampleClass(p) { 
 
    if (!document.getElementById){ return; }
 
    this.elem = document.getElementById(p);
};
 
ExampleClass.prototype = {
 
    // class variables:
    elem: null,
    hoverSize: '2em',
    active: false,
 
    // functions:
    setActive: function(s) {
        this.active = s;
    },
 
    setHoverSize: function(size) {
        this.hoverSize = size;
    },
 
    getHoverSize: function(size) {
        return this.hoverSize;
    },
 
    hover: function() {
        this.style.fontSize = exampleObject.getHoverSize();
        this.style.fontWeight = 'bold';
        this.style.color = '#FFFFFF';
        this.style.backgroundColor = '#43A5E7';
    },
 
    restore: function() {
        this.style.fontSize = '1em';
        this.style.fontWeight = 'normal';
        this.style.color = '#000000'; // black
        this.style.backgroundColor = '#EFEFEF';
    },
 
    init: function() {
 
        this.setActive(true);
 
        // attach events:
        if (this.active){
            this.elem.onmouseover = this.hover;
            this.elem.onmouseout = this.restore;
        }
 
    }
}
Snippet Details



// init. the "ExampleClass"
var exampleObject = new ExampleClass('example');
 
// call a class function:
exampleObject.setHoverSize('1.5em');
 
// call the init function
exampleObject.init();
 
 
 
// put some text into the example div:
document.write('Hover your mouse over here :-)');

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

cihan August 03, 2008 at 13:02
i try it,
but i had an error.

"this.elem is null or not object"