Putting Javascript into CSS

32,985

Solution 1

You can, but you really ought not to. Instead, use separate script files which happen to correspond to the CSS files you use. Maybe ask another question where you lay out a specific scenario where you're trying to solve a specific problem, and we can probably tell you the practice that's generally done to solve it.

Solution 2

There is a work around...

It not putting script in pure CSS code, but have a script to generate CSS Depending what scripting language you are using (eg PHP) your link to CSS file should look like:

<link href="/styles.php" media="screen" rel="stylesheet" type="text/css" />

you can even add params like:

<link href="/styles.php?type=main" media="screen" rel="stylesheet" type="text/css" />

and in you styles.php what should look like CSS file with a few exceptions:

body {
     <?php if ( $_GET['type'] == 'main' ) echo color: BLACK; else color: RED; ?>
  ......... 
}
Share:
32,985
Eric
Author by

Eric

Updated on December 29, 2020

Comments

  • Eric
    Eric over 3 years

    I've been thinking about something. On my forum, there are default CSS codes that the users can choose from. This changes everything from background to text color. I have a javascript code. Is it possible to make it so that the javascript is part of the CSS, so that if a certain CSS code is defaulted, then part of it is that javascript?

  • grahamparks
    grahamparks over 13 years
    There are quite a few different ways to embed JS in CSS. See e.g. stackoverflow.com/questions/3607894/…
  • Mike Samuel
    Mike Samuel over 13 years
    You should never put JS into CSS for performance/compatibility reasons, but you should not assume that hackers can't for the reasons grahamparks links to.