Css code inside JS file - javascript

I remember from somewhere some simple way to use css code inside JS file, but can't remember how exactly.
Obviously simply putting the css code inside JS file won't work, I guess there's a need for some comments or something like that.
*Note: I don't want to use JS to render a <link...> for a css file. I want load JS file normally with <script...> and inside a *.js file I want include pure css code, as it would appear normally in *.css file.

$("#id").css("parameter","property");
example..
$("#id").css("border","1px solid");
for multiple css..
$("#id").css({
'font-size' : '10px',
'width' : '30px',
'height' : '10px'
});
better to use
addClass( )
function.. for multiple css property..

Nice little function to add Internal CSS Block to document
function createStyleNode(cssText, options, doc) {
doc = doc || document;
var style = doc.createElement('style');
style.type = 'text/css';
if(options && options.id){
style.id = options.id;
}
if (style.styleSheet){
style.styleSheet.cssText = cssText;
} else {
style.appendChild(doc.createTextNode(cssText));
}
return style;
}
cssText = 'body {color: red}';
head.appendChild(createStyleNode(cssText, {'id': 'stylesFromJS'}));
Adding Ids will be useful, if you are planning to delete / replace them later from JS.

Related

How to get style of a div from javascript file

Iam new to javascript, I have given style for a div by using javascript in one js file and i want to get that style from another js file. how it is possible??
when i used
var height= $("#searchComment").css("height");
and on alerting the result it is get like 'undefined'.
if this style is given in html it returns correctly.
test1.js and test2.js are included in index.html
In test1.js ihave given styling to a div of id 'searchComment'
$( "#parentDiv").append("<div class='ui-li-desc' id='searchComment' style='height:50px; width:40 px'></div>");
and in another js file test2.js i want to get the style of div of id 'searchComment'.
how can i get this style?? please help me.
Thank you
use jquery selector and then change css:
$('.number').css({'font-size': '12px', 'text-align': 'left'});
You have to give ID for that div by using the id you can get it from other JS
Limitation :
Both js should be using in that HTML file.
Before using id of <div> you have to create that div
Ex :
test1.js
$("#commentList").append(<div class='number' id="mydiv" style='font-size: 18px;
text-align: justify; direction: rtl; float: right; width: 12%; padding-top:75px;'>
some Variable</div>);
test2.js
document.getElementById("mydiv").style;
You can change of any elements style from any file, But the standard practice is to add class instead of changing style of an element. To add class you can use .addClass('new-class') jQuery function. And put all your style for new class in separate CSS file. And if you just want to add style anyway without caring about standard, then you can use .css jquery function.
$(".number").css({
'attribute1': value,
'attribute2': value,
});
i think you want the description of the css class use. refer the post
function getStyleRules(className) {
var class = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < class.length; x++) {
if (class[x].selectorText == className) {
(class[x].cssText) ? alert(class[x].cssText) : alert(classes[x].style.cssText);
}
}
}
getStyleRules('.YourClassName');
click here

How to dynamically set and modify CSS in JavaScript?

I have some JavaScript code that creates some div elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css file, I would like to set the CSS className of my element and then dynamically inject some values into the defined CSS property.
Here is what I would like to do :
style.css:
.myClass {
width: $insertedFromJS
}
script.js:
var myElement = document.createElement("div");
myElement.className = "myClass";
I want to do something like this but at that point myElement.style.width is empty
myElement.style.width.replaceAll("$insertedFromJS", "400px");
I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.
If I understand your question properly, it sounds like you're trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can't do that in the way you're trying to do it. In order to do that, you'd have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that's a really overly-complicated way to go about doing something that...
myElement.style.width = "400px";
...can do for you in a couple of seconds. I know it doesn't really address the issue of decoupling css from js, but there's not really a whole lot you can do about that. You're trying to set css dynamically, after all.
Depending on what you're trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.
Setting the style, might be accomplished defining the inner-page style declaration.
Here is what i mean
var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.
if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules) // Standards Compliant {
csses = document.styleSheets[0].cssRules;
}
else {
csses = document.styleSheets[0].rules; // IE
}
for (i=0;i<csses.length;i++) {
if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
{
thecss[i].style.cssText="color:#000";
}
}
could you use jQuery on this? You could use
$(".class").css("property", val); /* or use the .width property */
There is a jQuery plugin called jQuery Rule,
http://flesler.blogspot.com/2007/11/jqueryrule.html
I tried it to dynamically set some div sizes of a board game. It works in FireFox, not in Chrome. I didn't try IE9.

lightweight dialog plugin that doesn't require css

I'm looking for a lightweight dialog plugin that doesn't require css.
I need it for a userscript, which means I can't include a css file
Any ideas?
You could dynamically inject a css file from a remote domain, which is what disqus does, for example.
var link = document.createElement('link')
link.rel = 'stylesheet'
link.href = 'http://yourhost.com/your.css'
You'd make to make sure your css has low chance of clashing with your user site's styles by restricting the styles using id or class names.
you can simply set the innerHTML of a style tag created via javascript. In this way you obtain an inlined stylesheet.
E.g.
var styleText = "body { background-color: red } div { color: lime }";
var styleBlock = document.createElement("style");
styleBlock.innerHTML = styleText;
document.head.appendChild(styleBlock);
Another idea is to use a dataURI of a css file:
E.g.
var linkEl = document.createElement("link");
linkEl.href = "data:text/css;base64,Ym9keSB7IGJhY2tncm91bmQtY29sb3I6YmxhY2sgfQo=";
linkEl.rel = "stylesheet";
linkEl.type = "text/css";
document.head.appendChild(linkEl);

How to check if a css rule exists

I need to check if a CSS rule exists because I want to issue some warnings if a CSS file is not included.
What is the best way of doing this?
I could filter through window.document.styleSheets.cssRules, but I'm not sure how cross-browser this is (plus I notice on Stack Overflow that object is null for styleSheet[0]).
I would also like to keep dependencies to a minimum.
Is there a straightforward way to do this? Do I just have to create matching elements and test the effects?
Edit: If not, what are the cross-browser concerns of checking window.document.styleSheets?
I don't know if this is an option for you, but if it's a single file you want to check, then you can write your error message and toggle the style to hide it in that file.
<span class="include_error">Error: CSS was not included!</span>
CSS file:
.include_error {
display: none;
visibility: hidden;
}
I test for proper CSS installation using javascript.
I have a CSS rule in my stylesheet that sets a particular id to position: absolute.
#testObject {position: absolute;}
I then programmatically create a temporary div with visibility: hidden with that ID and get the computed style position. If it's not absolute, then the desired CSS is not installed.
If you can't put your own rule in the style sheet, then you can identify one or more rules that you think are representative of the stylesheet and not likely to change and design a temporary object that should get those rules and test for their existence that way.
Or, lastly, you could try to enumerate all the external style sheets and look for a particular filename that is included.
The point here is that if you want to see if an external style sheet is included, you have to pick something about that style sheet that you can look for (filename or some rule in it or some effect it causes).
Here is what I got that works. It's similar to the answers by #Smamatti and #jfriend00 but more fleshed out. I really wish there was a way to test for rules directly but oh well.
CSS:
.my-css-loaded-marker {
z-index: -98256; /*just a random number*/
}
JS:
$(function () { //Must run on jq ready or $('body') might not exist
var dummyElement = $('<p>')
.hide().css({height: 0, width: 0})
.addClass("my-css-loaded-marker")
.appendTo("body"); //Works without this on firefox for some reason
if (dummyElement.css("z-index") != -98256 && console && console.error) {
console.error("Could not find my-app.css styles. Application requires my-app.css to be loaded in order to function properly");
}
dummyElement.remove();
});
I would use a css selector like this from within your jquery widget.
$('link[href$="my-app.css"]')
If you get a result back it means there is a link element that has a href ending with "my-app.css"
Next use this function to validate a specific css property on an element you are depending on. I would suggest something specific to you styles like the width of a container rather something random like -9999 zindex
var getStyle = function(el, styleProp) {
var x = !!el.nodeType ? el : document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
return y;
}
Like this
getStyle($('#stats-container')[0], "width")
or
getStyle("stats-container", "width")
If you are worried about not being able to edit other people's stylesheets, you can proxy them through a stylesheet of your own, using import
#import url('http://his-stylesheet.css');
.hideErrorMessage{ ... }
This is enough if you just want to know if your code is trying to load the stylesheet but won't help if you need to know if the foreign stylesheet was then loaded correctly.

How to make CKEditor render text with a CSS?

I have a CKEditor used to edit a text in a web-page.
In the web-page, the text renders in its context and therefore follows the page CSS formatting.
My question is how to tell CKEditor to apply a CSS style-sheet to the editor rendering ? Without of course changing the generated source ?
My code :
<textarea class="ActuContent" name="actu-content" cols="100" rows="20">my content></textarea>
<script type="text/javascript">
window.onload = function()
{
CKEDITOR.replace( 'actu-content' );
};
</script>
and my CSS :
.ActuContent{
padding:10px 10px 10px 10px;
color:#416a8b;
font-size:1.6em;
}
And my CKEditor Config.js file only contains the toolbar config.
CKeditor does not apply the settings of ".ActuContent" to its rendering ...
The actual best answer to this question would be:
CKEDITOR.config.contentsCss = '/mycustom.css';
CKEDITOR.replace('myfield');
Because you probably would like to have different styles in different editors. If you change the main content.css like Jalil did, you would not be able to do that.
I found a very easy way to answer my question :
the content.css file in CKEditor directory !
I only had to put in the style I wanted to be applied inside the Editor :
body {
color: #416a8b;
font-family: Arial;
font-size: 18px;
font-weight: 400;
text-align: left;
}
That's all :-)
See this posting:
CKEditor: Class or ID for editor body
The solution posted by nemisj will set the class name onto the body of the editor's editable area.
You can do this in an editor onload function. Call this before you call .replace.
CKEDITOR.on( 'instanceReady', function( ev )
{
CKEDITOR.instances.e1.document.$.body.className = "foo";
});
Sometimes when I need to set some styles to the CKEditor on the fly, for example depending on user settings, I use setStyle() and setStyles() functions on the editor's body object. Sample code:
var editor = CKEDITOR.instances.editor1;
var size = ... // assign size value
editor.document.getBody().setStyle('font-size',size);
Another sample:
var editor = CKEDITOR.instances.editor1;
var styles = {
"font-family": "Arial",
"color": "#333"
};
editor.document.getBody().setStyles(styles);
CKEditor uses a DIV with normal HTML elements to represent the text you're editing. Just have a look at the content of this DIV and write a appropriate style sheet.
Of course, this only works if you don't modify the output of CKEditor before you render it.
If you change content.css file you may discover that it's been cached. It's not a trivial task to refresh it in your browser since CKEDITOR.timestamp is added only to js files. I came up with the following solution:
// force to update all plugin files and styles
CKEDITOR.timestamp = '25062014';
CKEDITOR.config.contentsCss = CKEDITOR.config.contentsCss + '?' + CKEDITOR.timestamp;

Categories

Resources