0

I am using jquery to modify css of a div element on pressing a button. I noticed the css getting inline to the HTML. How can I prevent the style from getting inline ?

<style media="" data-href="../../dist/css/flat-ui.css">...</style>

These style tags appear on rendering.

Karthick
  • 47
  • 6

2 Answers2

0

Link your stylesheet in head

<head>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
Rahul
  • 493
  • 6
  • 27
  • Yes, I've already done that. The style tag get appended while rendering. It makes sense to become inline because that's the only way jquery can dynamically push css. – Karthick Jan 23 '17 at 06:28
  • You're right and there is no way(that I know of) to prevent that from happening. – Rahul Jan 23 '17 at 06:46
0

I am using jquery to modify css of a div element on pressing a button.

The most obvious would of course be to add/remove/toggle a class with a predefined rule, like this,

CSS

.wider {
  width: 500px;
}

Script

$( "element" ).toggleClass( "wider" );

but if that is not what you look for, you can add a style element dynamically, to override an existing rule

JS

function loadStyle(css) {
  var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
  style.id = 'lastinbody';
  style.type = 'text/css';
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  document.querySelector('body').appendChild(style);
}

Usage

loadStyle('.item { color: red; }');

I noticed the css getting inline to the HTML.

If you want the style being added to the head, do like this

JS

function loadStyle(css) {
  var style = document.querySelector('head style[id="addedinhead"]') || document.createElement('style');
  style.id = 'addedinhead';
  style.type = 'text/css';
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  document.querySelector('head').appendChild(style);
}

And here is how to push a CSS file

var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.media = 'screen';
style.href = 'css-file-path';
document.querySelector('head').appendChild(style);

And this one shows how to add to an existing linked stylesheet

HTML

<head>
  <link title="customCSS" rel="stylesheet" type="text/css" href="style.css">
</head>

JS

function setStyleSheetRule(title, rule) {
  for(var i=0; i<document.styleSheets.length; i++) {
    var sheet = document.styleSheets[i];
    if(sheet.title == title) {
      sheet.insertRule(rule, sheet.cssRules.length);
    }
  }
}

setStyleSheetRule('customCSS', '.have-border { border: 1px solid black;}')

Read more: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule

Asons
  • 84,923
  • 12
  • 110
  • 165