DOM Programming

From Elvanör's Technical Wiki
Jump to navigationJump to search


  • The W3C specification allows for dynamic modification of CSS stylesheet. Firefox supports this, and IE too with proprietary, non standard APIs (not in Prototype, unfortunately). The main idea is to do something like:
document.styleSheets[0].insertRule(myCSSRule, 0);
  • In Firefox, there are several bugs. First you should only use insertRule() and removeRule. You can access the CSS <style> element directly and call update() on it, but that won't work a lot of times. Second, even when using the APIs, after an Ajax call it seems that delaying actions on the stylesheet is necessary, else some updates don't work (particularly on the background-image CSS property). You can use the delay() function of Prototype to achieve that.
  • It also seems impossible to access the object document.styleSheets[0].cssRules in Firefox 2. I got access violations.



  • This event is tricky and allows the developer to push an alert when the user wants to close the tab OR navigate away from the page (it can be directly via the URL bar or via following a link). If the user clicks on the "Stay on page" button, the browser cancels the action.
  • Note that you cannot obtain the result of the modal dialog, eg you don't know which button an user clicked on.
  • Typically you want to distinguish between a click on a page link or a closing of the tab. This can be done via the following trick: register a click event listener on the whole window, then inside the callback handler remove the beforeunload listener. Thus if an user clicks on the page, you won't get the alert popup, whereas if he closes the tab, the click event won't be fired (it is not considered inside the window chrome) and thus the alert will be shown. Note that usually you need to reregister the beforeunload listener 300ms after the click.