0

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.)

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

0

Here is a very simple approach

// define the object
var Interface = function () {

    var interface = document.getElementById("interface"); // just an example

    // your new methods
    this.setBackground = function (color) {
        interface.style.backgroundColor = color;
    }

    // rest of your code
}

now you can make use of it

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

1 Comment

I already tried something similair to that, but the problem is that the "document" object won't work inside a method...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.