Short Tag – Web Development Blog

Entries for August, 2011

Remove all children from an element using XUL Javascript

This is a small script that will remove all children of a XULElement:

var elem = document.getElementById(‘my_element’);
while (elem.firstChild)
elem.removeChild(elem.firstChild);

Open an URL with XUL and XPCom

Since the HTML <a> tag is not working in XUL we need another approach to open a URL.
You can use the function below in your project:

function gotoUrl(url)
{
var nsioservice= Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);

var uri = nsioservice.newURI(url, null, null);

var eps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
.getService(Components.interfaces.nsIExternalProtocolService);

eps.loadURI(uri, null);
}

Use it like this:

gotoUrl(‘http://www.short-tag.info’);

How to get an elements XY position with XUL javascript

In the XPCOM library there is a function called getBoundingClientRect() that is accesible for any visible element.
So, if you want to get a XUL element’s position:

var rect = item.getBoundingClientRect();
var x = rect.left;
var y = rect.top;
var height = rect.height;
var width = rect.width;

Remember, ‘item’ can be any XULElement. For example:

var item = document.getElementById(‘myObject’);
var rect = item.getBoundingClientRect();
var x [...]