Skip to content

Instantly share code, notes, and snippets.

@xero
Last active October 22, 2021 08:03
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save xero/4678977 to your computer and use it in GitHub Desktop.
Save xero/4678977 to your computer and use it in GitHub Desktop.
css style injection via jQuery. basically calling body/head append with a style tag and your own css will add a new tag and your styles to the bottom of the page/head and override any existing ones. why is this useful? imagine embedding a single js file into the page and defining your own styles (think widget for a client), or loading css via aj…
<!DOCTYPE html>
<html>
<head>
<title>css injection | xero.nu</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
body{
font: normal 12pt "Times New Roman", serif;
background: #ccc;
color: #000066;
}
a, a:visited {
color: #0000ff;
}
</style>
</head>
<body>
<h1>css injection</h1>
<p>hello world! this is <a href="http://xero.nu/">xero</a>!</p>
<p>click the button below and inject new css styles into the page via javascript!</p>
<p><input type="button" value=" inject! " onclick="test()" />
<script type="text/javascript">
function test() {
/* calling body append will add your new styles to the bottom of the page and override any existing ones */
$('head').append('<style type="text/css">body{font:normal 14pt Arial, Helvetica, sans-serif;background:#000;color:#fff}a,a:visited{color:#ccc;text-decoration:none;border-bottom:1px solid #00ff00}a:hover{color:#00ff00;border-color:#ccc}</style>');
}
</script>
</body>
</html>
@ghanhass
Copy link

+1

@bleedkaga
Copy link

+1

@anuranjanverma
Copy link

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment