Skip to content

Instantly share code, notes, and snippets.

@dandean
Created August 3, 2009 18:11
Show Gist options
  • Save dandean/160728 to your computer and use it in GitHub Desktop.
Save dandean/160728 to your computer and use it in GitHub Desktop.
RuntimeIframe Class (or Ajax.IFrame, or something... ) for dynamically loading iframes...
/**
* class RuntimeIframe (or Ajax.IFrame, or something... )
**/
var RuntimeIframe = Class.create({
/**
* new RuntimeIframe(options);
* - options (Object): Configuration options; currently limited to `width` and `height`
*
* Creates a new `RuntimeIframe`.
**/
initialize: function(options) {
this.element = new Element("iframe", {
frameBorder: 0,
style: "display:none;"
});
if (options) {
if (typeof options.width != "undefined") this.element.style.width = options.width + "px";
if (typeof options.height != "undefined") this.element.style.height = options.height + "px";
}
this.element.name = this.element.identify();
document.body.insert(this.element);
},
/**
* RuntimeIframe#load(url, options) -> this
* - url (String): The url to load in the iframe
* - options (Object): Configuration for the request.
*
* Loads the iframe using the given URL with the given Options.
*
* <h4>Common options</h4>
*
* * `method` ([[String]]; default `get`): The HTTP method to use for the
* request. The other common possibility is `post`.
* * `parameters` ([[String]]): The parameters for the request, which will be
* encoded into the URL for a `get` method, or into the request body for the
* `post` method. This should be provided as a plain [[Object]].
**/
load: function(url, options) {
url = url || "about:blank";
options = options || {};
var opts = {
method: options.method || "get",
parameters: options.parameters || {}
};
if (opts.method == "post") {
var form = new Element("form", {
action: url,
method: "post",
target: this.element.name,
style: "visibility: hidden; position: absolute; top: 0; left: 0"
});
document.body.insert(form);
for (var key in opts.parameters) {
form.insert(new Element("input", {
type: "hidden",
name: key,
value: opts.parameters[key]
}));
}
form.submit();
form.remove();
} else if (opts.method == "get") {
this.element.src = url + ((Object.keys(opts.parameters).length > 0) ? "?" + Object.toQueryString(opts.parameters) : "");
}
return this;
},
/**
* RuntimeIframe#unload() -> this
*
* Unloads the iframe by setting its `src` property to "about:blank"
**/
unload: function() {
this.element.src = "about:blank";
return this;
},
show: function() {
this.element.show();
return this;
},
hide: function() {
this.element.hide();
return this;
},
toString: function() { return "[object RuntimeIframe]"; }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment