Include javascript via css?
No, this is not possible, and nor should it be. Separate your application logic from your styling.
For when the two need to interact, you can detect certain styles with JavaScript and load various other JavaScript files from there.
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.
How to embed Javascript in CSS?
In IE, and only IE, you can use CSS expressions:
width: expression(blah + "px");
Then width
becomes whatever's inside the brackets.
This only works in IE, though - so don't use it. Use a JS function to assign the elements the style with element.style.width
or similar.
For example:
<script type="text/javascript">
document.getElementById('header').style.width = (100 * 2) + 'px';
</script>
How to load up CSS files using Javascript?
Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute
unfortunately IE6 doesn't support it consistently.
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.example/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
This example checks if the CSS was already added so it adds it only once.
Put that code into a JavaScript file, have the end-user simply include the JavaScript, and make sure the CSS path is absolute so it is loaded from your servers.
VanillaJS
Here is an example that uses plain JavaScript to inject a CSS link into the head
element based on the filename portion of the URL:
<script type="text/javascript">
var file = location.pathname.split( "/" ).pop();
var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";
document.getElementsByTagName( "head" )[0].appendChild( link );
</script>
Insert the code just before the closing head
tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (.js
) file will cause a Flash of unstyled content (FOUC) to appear.
How to use Javascript variables in CSS?
No, you can not use javascript variables inside css, but you can change the style of an element dynamically via javascript's DOM elements, style property.
document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";
In your case:
var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;
//Activates Slowdown
window.onload = loop();
//Speed up
function spin() {
if (speed < 0) {
speed = speed + 10;
loop()
} else {
speed = speed + 10;
}
}
spinner.addEventListener('click', spin);
//Slowdown
function loop() {
setTimeout(
function slow() {
speed = speed - slowSpeed;
document.getElementById("speed").innerHTML = speed;
if (speed > 0) {
loop();
}
document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";
}, 1000)
}
//Selectors
function wheel() {
spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}
EDIT:
As per Vladu Ionut's answer , we can use variables in CSS.
Advantages:
- It works in modern browsers.
Disadavantage:
- It does not work in old browsers like:
- IE
- EDGE <= 15
- Chrome < 49, etc..
...
...
EDIT:2, Update the code, as per the comment
var spinnerImg = undefined; var speedTxt = undefined; var wheelImgUrl = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"; var spiralImgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png"; var speed = 0; var maxSpeedChange = 10; var slowSpeed = 2; var speedParam = slowSpeed;
/** * Function to change the image to wheel * * @Arguments: none * * @Returns: void */ function changeToWheel() { spinnerImg.src = wheelImgUrl; }
/** * Function to change the image to spiral * * @Arguments: none * * @Returns: void */ function changeToSpiral() { spinnerImg.src = spiralImgUrl; }
/** * Function to update speed display * * @Arguments: void * * @Returns: void */ function updateSpeedTxt() { speedTxt.innerHTML = speed; }
/** * @Function to rotate the image * * @Arguments: void * * @Returns: void */ function rotateImg() { spinnerImg.style.transform = "rotate(" + speed + "deg)"; }
window.addEventListener("load", function() { spinnerImg = document.getElementById("spinner"); speedTxt = document.getElementById("speed"); speed = speedParam; setInterval(function() { updateSpeedTxt(); rotateImg(); if (speedParam > slowSpeed) { speedParam -= 0.05; } if (speedParam < slowSpeed) { speedParam = slowSpeed; } speed += speedParam; }, 50);
spinnerImg.addEventListener("click", function() { speedParam += maxSpeedChange; });
});
#spinner { width: 500px; transform-origin: center; }
<!DOCTYPE html><html> <head> </head> <body> <div id="spinnerContainer"> <img id="spinner" src="http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"/> <h4 id="speed">N/A</h4> </div> <div id="selectors"> <ul> <button onclick="changeToWheel()">Wheel</button> <button onclick="changeToSpiral()">Spiral</button> </ul> </div> <footer>
</footer> </body></html>
Where should I put the CSS and Javascript code in an HTML webpage?
In my opinion the best practice is to place the CSS file in the header
<head>
<link rel="stylesheet" href="css/layout.css" type="text/css">
</head>
and the Javascript file before the closing </body>
tag
<script type="text/javascript" src="script.js"></script>
</body>
Also if you have, like you said two CSS files. The browser would use both. If there were any selectors, ie. .content {}
that were the same in both CSS files the browser would overwrite the similar properties of the first one with the second one's properties. If that makes sense.
How to get Javascript variable value into CSS?
I'm not sure wether that's the best way to achieve what you want to do, as you could also use a container element and change its content directly:
const screenContentElement = document.getElementById('screen__content'); function pad(value) { const str = value + ''; return str.length === 2 ? str : '0' + str;}
function clock(){ var d = new Date(); return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());}
setInterval(() => { screenContentElement.innerText = clock();}, 1000);
#screen { font-family: Arial, sans-serif; position: relative; height: 100%; width: 100%; background: #98E8EE; text-align: center; padding: 2rem 0;}
#screen__content { color: #F9F5F4; font-size: 40px;}
<div id="screen" class="screen"> <span id="screen__content"></span></div>
Related Topics
Can't Figure Out Why Page Loads at Bottom? Angular Ui-Router Autoscroll Issue
A Way to Count Columns in a Responsive Grid
Targeting Pure Elements in Next.Js with CSS Modules
Partial Password Masking on Input Field
How to Animate the Opacity of the Background of a Div
Show a Bootstrap Modal If Option Is Selected
Is "Localstorage" in Firefox Only Working When the Page Is Online
How to Open Bootstrap Modal in Ajax Success
Javascript: Change CSS File Dynamically + Cookie
Filling an Svg Path with Multiple Colors
CSS Reveal from Corner Animation
List Reorder Animation with Angularjs
Why Do People Minify CSS and JavaScript, When We Have Gzip
Find Td with Specific Text, and Operate on the Td Right After That One
Make a Div Scroll When I Reach a Certain Point