Suppose I have a CSS file custom_style.css and a HTML file custom_render.html.
custom_render.html contains some input field to take input from user and than generates CSS styles based on those input.
Now I want to store those generated CSS styles in a CSS file called custom_style.css [that is located in my projects root directory], so that I can show the users a preview/output of their selections.
After googling I got a way to store those generated CSS in the same file [custom_render.html] using JavaScript, but I want to store them in custom_style.css.
Can anyone tell me how can I write CSS Styles in CSS files using JavaScript or other JavaScript framework.
- Thanks
Well, you can modify the parameters of objects in your stylesheets. For example:
document.styleSheets[i].rules[j].style.marginTop = "100px";
i being the number corresponding to the sheet you want to edit
and
j being which element rule you want to change the parameter for.
In this case I used marginTop as a paramater and 100px as a value but it could be whatever valid CSS you would like.
simple... (assuming this is what you trying to achieve)
var elem = document.getElementsByClassName('target_class');
// should use for loop to assign click event to each element containing this class
elem[0].onclick = function() {
elem[0].style.background = 'green';
elem[0].style.opacity = '0.2';
}
<div class="target_class" style="width: 200px; height: 200px; background: red"></div>
insertRule(rule, index)
This will inserts a new rule to the stylesheet, where the parameter "rule" is a string containing the entire rule to add (ie: #myid{color: red; border: 1px solid black}), and "index", an integer specifying the position within cssRules[] to insert the new rule.
document.styleSheets[0].insertRule("p{font-size: 20px;}", 0) //add new rule to start of stylesheet
Related
I have a component under test that behaves differently based on a current css of the site. I would like to add a css for a single test. Is it possible to add it without creating a file, like a temporary css for the test only?
Is it possible to add a css code in the qUnit test function?
You can create style node dynamically with desired CSS rule.
var tempCSS = document.createElement("style");
tempCSS.type = "text/css";
tempCSS.innerHTML = ".myClass { background-color: red; }";
document.body.appendChild(tempCSS);
<div class="myClass">yahoooooooo</div>
How should I highlight the text in view from the URL link with id match to that particular id or text?
I have some 50 list out of that I need to highlight that particular id or text
I don't know whether I should write in jquery or with codeigniter 3.
Eg. localhost/example/admin/home/CL00074
Here is the pic which I want to highlight.
If you didn't understand, please let me know.
Check for refferal
You should probably use Code Igniter's the URI library, it'd look something like this:
$this->uri->segment(n)
But since this was a jQuery question, you'd use a hash and target it that way:
Update your routing: localhost/example/admin/home#CL00074
// if hash exists, check and highlight
if (window.location.hash) {
var hash = window.location.hash.replace('#', '');
$('td[id='+ hash +']').addClass('selected');
}
Possibility two
This is use Segment
Follow link
2.This is use Route
Follow link
Add to script config/route.php
$route['admin/home/(:any)'] = 'Controllername/functionname/$1';
Say your link would be localhost/example/admin/home#CL00074 and your id goes into the html like this:
<div id="CL00074">
</div>
, you could use only css to highlight or style that particular element (div, h1, li or whatever) of the page.
Use :target css identifier:
:taget{
color: black;
border: 1px solid red;
}
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
Is it possible to compute resulting css style on the element manually (without need to render it)?
Lets say I'm supposed to have an HTML structure:
<p style="some_style1">
<span style="some_style2">
<span style="some_style3">
TEXT
</span>
</span>
</p>
I know what are some_style1, some_style2, some_style3 in terms of JS object (for example i have data for each element like: {font: 'Times New Roman' 12px bold; text-align: center;})
I want to MANUALLY (without need to render in browser the whole structure) compute resulting style that will effect "TEXT".
What algorithm (or solution) should I use?
There exist browsers that don't need rendering in a window (headless browser). You can load a page and query what you want. It won't be easier than in a normal browser to obtain what you ask though.
JSCSSP is a CSS parser written in cross-browser JavaScript that could be a first step to achieve what you want from scratch or quite. Give it a stylesheet and it'll tell you what a browser would've parsed. You still must manage:
the DOM,
inheritance of styles,
determine which rules apply to a given element with or without class, id, attributes, siblings, etc
priorities of selectors
etc
Its author is D. Glazman, co-chairman of the W3C CSS group and developer of Kompozer, NVu and BlueGriffon so it should parse CSS as expected :)
The simplest thing I can think of is to wrap the whole thing in a a container that you set display: none on, and append it to the DOM. The browser won't render it, but you'll then be able to query the computed style.
Here's an example showing how jQuery can't find the style information when the structure isn't connected to the DOM, but when it is, it can:
jQuery(function($) {
// Disconnected structure
var x = $("<p style='color: red'><span style='padding: 2em'><span style='background-color: white'>TEXT</span></span></p>");
// Get the span
var y = x.find("span span");
// Show its computed color; will be blank
display("y.css('color'): " + y.css('color'));
// Create a hidden div and append the structure
var d = $("<div>");
d.hide();
d.append(x);
d.appendTo(document.body);
// Show the computed color now; show red
display("y.css('color'): " + y.css('color'));
// Detach it again
d.detach();
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
});
Live copy | source
I can't guarantee all values will be exactly right, you'll have to try it and see; browsers may defer calculating some things until/unless the container is visible. If you find that some properties you want aren't calculated yet, you may have to make the div visible, but off-page (position: absolute; left: -10000px);
I found some articles about this: Can jQuery get all styles applied to an element on Stackoverflow.
Also this one on quirksmode: Get Styles that shows the following function:
function getStyle(el,styleProp)
{
var x = 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;
}
This allows you to query for style properties
Styles override each other in the order in which they're defined: So anything in some_style3 that overrides the same selector in some_style2, say, will do. Otherwise, it will just be a union of the sets of selectors.
EDIT Some selectors won't override, but instead act relatively on a previous definition, so you've got to be careful about that.
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.