Using Javascript in CSS

javascript set style class
javascript change css class
javascript change css class property
use javascript variable in css
how to pass a javascript variable value to an inline css style
dynamically change css class with javascript
javascript add css
add css to html with javascript

Is it possible to use Javascript inside CSS?

If it is, can you give a simple example?

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 behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue 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 Javascript in CSS, 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  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 behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL.

I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

CSS-in-JS, and host it on your own server (just like your *. JavaScript can also be used to load a CSS file in the HTML document.

To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):

styles.css.php:

body
 {
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
 }

This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:

user_theme.css.php:

body
 {
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
 }

#panel
 {
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
 }

Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.

How To Add JavaScript to HTML, is generated (usually as a <style> element) and attached into the DOM. CSS Variables and JavaScript We recently came across Lea Verou’s slider polyfill which expresses an interesting use of CSS Variables to communicate between JavaScript and CSS. Historically, if you wanted to control CSS with a variable or function in JavaScript, your only option was to essentially write the CSS in JavaScript:

IE supports CSS expressions:

width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

Manipulating CSS with JavaScript · WebPlatform Docs, HTML components work on sites using Internet Explorer when they are on the same domain as the CSS style tag or style sheet displayed. You can get CSS values in JavaScript through two methods: The style property; getComputedStyle. The style property only retrieves inlined CSS values while getComputedStyle style retrieves computed CSS values. If this lesson has helped you, might enjoy Learn JavaScript, where you’ll learn how to build anything you want from scratch. Enrollment for Learn JavaScript opens in July 2018 (next week!).

Not in any conventional sense of the phrase "inside CSS."

Executing JavaScript Inside CSS, As of 2016, CSS Variables are fully usable in Chrome and Firefox, and IE has declared their intention to implement it as well. Like many of the new JavaScript  Most names in CSS would get JavaScript's seal of approval, so you can just use them straight-up from the carton. There are a few things to keep in mind, though. To specify a CSS property in JavaScript that contains a dash, simply remove the dash. For example, background-color becomes backgroundColor,

Communicating Between JavaScript and CSS Using CSS Variables , The people who use programming languages are often called programmers or developers. The things we tell software using a programming  jQuery css() Method. The css() method sets or returns one or more style properties for the selected elements.

Web Design 101: How HTML, CSS, and JavaScript Work, Setting the Style Directly. Every HTML element that you access via JavaScript has a style object Duration: 8:07 Posted: Aug 15, 2019 The <script> tag is used to define a client-side script (JavaScript). The <script> element either contains script statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.

Setting CSS Styles using JavaScript, Set CSS styles with javascript. Inline styles. The most straightforward path. Global styles. Another option is to create <style> tag, fill it with CSS rules and append the tag to the DOM. CSSOM insertRule. Third option is less known. Constructable Stylesheets (July 2019 update) It's now possible to create CSSStyleSheet As we’ve seen, manipulating CSS transitions can be simplified using JavaScript. If you don’t end up getting the results you want with CSS animations, you can try making it into a transition instead and working with it that way.

Comments
  • Some suggestions below mention Expressions in Internet Explorer - be sure NOT to use these.
  • Expressions in IE are evil - they are re-evaluated on every single event (mousemove, anyone?). Therefore, anywhere not-IE they'll silently fail, in IE, they'll slow down the page considerably.
  • (Not sure if asking on a old answer is helpful) I tried the XBL technique in Firefox 18, but it didn't work. Is it only accessible to Firefox extensions?
  • Also worth noting - HTML components aren't supported in IE after version 10
  • As of 2016, XBL can not be loaded via HTTP.
  • @JSmyth what about ꜰᴛᴘ and data ᴜʀɪ ?
  • @user2284570 Have not tried it but this page says: Note: XBL cannot be loaded over HTTP, so this technique is only useful for local content accessed using the file:/// scheme, or from add-on code. I'd be interested to see if you can get it working over data-uri/ftp/etc. This would perhaps mean CORS bypass.
  • key part there being 'only supported by IE'; unless that css file is being included via a conditional comment, it should be avoided.
  • It should be avoided in any case: developer.yahoo.com/performance/rules.html#css_expressions
  • Note also standards mode IE8 doesn't support expressions in CSS either.