JavaScript access elements from custom object

This must be a very stupid question, but I just can't get it to work.

I'm creating my own UIKit for iOS. (Website-kit which will allow iPhone-like interfaces).

But, I'm trying to create a JavaScript library, which can be used to change several elements of the document. For instance, set a custom background colour when the document loads.

I'm trying to do that with object-orientated JavaScript. Like this:

var UI = new Interface();
UI.setBackground("#000");

How could I achieve this? (So the custom "UI" Object, and (an example) on how to change the background color of the document, from INSIDE the object.)

Answers


You can save a reference to the DOM inside the JS object and rewrite it as needed.

function Interface() {
    this.setBackground = function (color) {
        this.pointTo.style.background = color;
    };
    this.pointTo = document.body;
}

You can initialize this by:

var UI = new Interface();
UI.pointTo = document.getElementById('some_id');
UI.setBackground("#000");
// Set another style, on a different element
UI.pointTo = document.getElementById('some_other_id');
UI.setBackground("#FFF");

This is a simple implementation and need to be allot smarter, but it should do the job.

Edit: Made a mistake in original posting, and fixed erroneous code. Also made an example: http://jsfiddle.net/HpW3E/


Like silverstrike's code, but you can pass the target object in the interface constructor to don't get trouble in the future.

function Interface(target) {
    target = target || document.body;
    this.setBackground = function (color) {
        target.style.background = color || 'white';
    };
}

Ok now you can do this:

var UI = new Interface(document.body);
UI.setBackground("#000");

or even in somecases that you are applying the interface in global scope !ONLY!:

var UI = new Interface(this.body);
UI.setBackground("#000");

Also will work as this:

var UI = new Interface();
UI.setBackground("#000");

Need Your Help

Get website's ID in IIS 6 using the command line

iis batch-file website iis-6 identifier

I need to get the website's ID by its name in IIS 6 in Windows server 2003. I did it using C# but later discovered that the server doesn't have the .Net framework installed. I just know the name of...

Windows Phone 8 - Twitter API

c# twitter windows-phone-8

I am doing some research and can't seem to find a definitive way to query Twitter's API to get a user's tweets on WP8 using C#.