Is there a way to execute javascript from inside a css file ?
IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behaviour, in which a separate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't execute JavaScript from CSS directly, but the effect is the same.
HTC with IE
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main()
function on the event ondocumentready
(referring to the HTC document's readiness.)
XBL with Firefox
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body
, it will execute immediately on page load.
Using CSS !important with JavaScript
Try this code using CSSStyleDeclaration.setProperty():
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].style.setProperty("background-color", "red", "important");
}
How do you add CSS with Javascript?
You can also do this using DOM Level 2 CSS interfaces (MDN):
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:
sheet.addRule('strong', 'color: red;', -1);
There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.
You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.
Injecting a CSS stylesheet using Javascript
If the stylesheet is a separate resource, (You've confirmed in a comment that it is), you link it with link rel="stylesheet"
:
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = "mystyle.css";
document.head.appendChild(link);
// Or document.querySelector("head").appendChild(link);
// But I don't think that's necessary on any vaguely-modern browser
(Can't really do a live example of this one with Stack Snippets.)
If you have it as a string, you apply it with a style
element:
var style = document.createElement("style");
style.appendChild(document.createTextNode("/*...style text here...*/"));
document.head.appendChild(style);
Live example:
var style = document.createElement("style");style.appendChild(document.createTextNode( "#p1 { background-color: yellow}"));document.head.appendChild(style);
<p id="p1">Altering style of first paragraph via Javascript.</p><p id="p2">Altering style of second paragraph via Javascript.</p>
Related Topics
How to Convert Base64 String to JavaScript File Object Like as from File Input Form
Intercept a Form Submit in JavaScript and Prevent Normal Submission
Chrome Counts Characters Wrong in Textarea With Maxlength Attribute
How to Add a ≪Script≫ Element to the Dom and Execute Its Code
How to Load an Entire HTML Document into a Document Fragment in Internet Explorer
Script Tag Create With Innerhtml of a Div Doesn't Work
What Is the Correct Syntax of Ng-Include
Getting Value of HTML Checkbox from Onclick/Onchange Events
How to Run JavaScript Before the Whole Page Is Loaded
Passing Form Data to Another HTML Page
Changing Element Style Attribute Dynamically Using JavaScript
Coordinates of Selected Text in Browser Page
Very Simple, Very Smooth, JavaScript Marquee
Programmatically Selecting Partial Text in an Input Field
Want to Add "Addeventlistener" on Multiple Elements With Same Class
Why Does Jquery or a Dom Method Such as Getelementbyid Not Find the Element