background: url(javascript:...) Hack

Test of Filter

This text will be green if the rule has been applied.

Code Syntax


#testElement {
   background-image: url("javascript: testElement.style.color = '#00cc00';");
   }
         

Browser Support / Behaviour

Applied By

Not Applied By

Destroyed

Unknown

Special Notes / Browser Specific Behaviour

This hack is usually used to extending CSS support in IE on Windows. For instance, extending :focus and :hover pseudo-classes to all elements (the CSS file in this example doesn't validate). Many more uses are probably possible. It can also be used to hide styles from browsers that don't allow the use of the javascript: protocol in urls used in CSS as is done in the example on this page.

This is hopelessly hacky mis-use of the background-image property. Though you can get this past the W3C validator, the url() value type allows only real urls and not psuedo-protocols like javascript:, view-source:, or about:. No matter how simple your embedded Javascript, it will result in code that is difficult to read and maintain. If you are tempted to use this method, consider other means. Even cleaner, non-validating methods such as using IE's proprietary expression() extension for simple Javascript or behaviour() extension for more complex code (with the actual functionality isolated in an .htc file) are preferable.

In some browsers, a delay may be noticed between the page beginning to render and the Javascript in the hack being parsed and executed.

More information