Javascript CSS visability - javascript

It seems that javascript only can ready inline css if i want to check if element is display:hidden getting it with:
el.style.display
But how to check if display:none is placed inside external CSS file?

You'll need to access the computed style of the element with getComputedStyle (standards-compatible browsers) or currentStyle (IE). Google for those terms for examples or use a framework such as jQuery, which provide wrappers for that.

It might be the backwards way and not helpful in this case, but anyway:
If you want to check out what's in the loaded CSS files, you can get the loaded stylesheets with var sheets = document.styleSheets;, and access the first one with sheets[0];
Then, get the rules from it:
var rules = sheets[0].cssRules ? sheets[0].cssRules : sheets[0].rules;
Then loop through the rules to check them out:
var rule, selector;
for (var idx=0, len=rules.length; idx<len; ++idx) {
rule = rules[idx];
selector = rule.selectorText;
if (!selector) {continue;}
console.log(selector+' => '+ rule.style.cssText);
}
This is more or less straight from David Flanagan's great book "Javascript, the Definitive Guide (5th ed.)"

if(el.style.display=='none') will work regardless of where the CSS is defined.

Related

Can I use javascript to change individual page css entries (as opposed to swapping stylesheets)?

I know it's possible to change css attributes on elements on the current page:
$('.changeMyStyle').css("color", "#FF0000");
But this won't affect new elements added after the change is made.
I know it's possible to remove, add, or swap out css stylesheets to re-style a page after it's been loaded:
$('link.swappableStylesheet').attr('href', 'path/to/new/style.css');
But this is a poor solution for changing one or two attributes, especially to programmatically-determined values (such as changing color from a colorpicker).
I could probably grab a stylesheet's raw data, search it, and modify it:
var sheet= document.styleSheets[0];
var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules; // IE compatibility
rules[0].style.padding= '0.32em 2em';
// assumes the first entry in the first stylesheet is the one you want to modify.
// if it's not, you have to search to find the exact selector you're looking for
// and pray it's not in a slightly different order
But that's also a poor solution and requires IE-compatibility hacks.
This linked answer also suggests appending another <style> element and adding css there. That could work for narrow cases, but it's still not ideal (and the answer is 5 years old, so new tools may be available now).
Is there a way to alter the page's css at a selector & attribute level instead of stylesheet level or DOM element level? jQuery and vanilla javascript solutions both welcome, as well as libraries designed to do this specifically. Ideally I'd like something that's as easy and versatile as
$(document).stylesheet('.arbitraryCssSelector.Here').put('color', '#FF0000');
...where .stylesheet('.Here.arbitraryCssSelector') would modify the exact same style entry.
Even Chrome's dev tools just modifies the stylesheet it's using when you make modifications or add new rules. There's not currently a way around it, but you can keep a dedicated stylesheet at the bottom of the page that you update with the newest rules. If it's empty or contains invalid rules it will just fall back to the current stylesheet. If any library exists out there this is how it would do it, and it's very little code.
I think the key to keeping it uncluttered is to simply keep overwriting one stylesheet instead of adding new stylesheets to the DOM.
document.getElementById("dynamic-color").addEventListener("input", function () {
document.getElementById("dynamic-styles").innerHTML = "label { color: " + this.value + " }";
});
label {
color: blue;
}
<label for="#dynamic-color">Change the label's color!</label>
<input id="dynamic-color" />
<style id="dynamic-styles"></style>

reset style inheritance not working in shadow dom

I'm using shadow dom to avoid my element's style from accidently affected by the host document,but it still inheritance some attributes from the parent,like the 'color','font-size','line-height',etc.
After searching google,I have found that there exists one attribute which can be used to achieve this,and it's the 'resetStyleInheritance' attribute.
I use the attribute like this:
var root = this.createShadowRoot();
root.resetStyleInheritance = true;
or add a 'reset-style-inheritance' attribute the the element,like:
<div reset-style-inheritance=true></div>
However,both cases didn't work.
I also found a bug report here:WebKit Bugzilla
My jsfiddle: http://jsfiddle.net/sangelee/90za0euy/1/
Why the resetStyleInheritance didn't work?Or are there any other solution to prevent style inheritance in shadow dom?Any help is appreciated!
ps.I'm using chrome 39,and just ignore other browsers.
First of all, the reset-style-inheritance attribute is now obsolete and should not be used. The shadow DOM is now not to be affected by light CSS anymore by default.
Your code contained an amount of glitches I get rid of (like you were creating the font-ruler prior to registering it, and you were handling attachedCallback while the proper event to handle is createdCallback.) The working version live is located here: http://jsfiddle.net/284au4nw/
A couple comments:
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var t = document.querySelector('#s-font-ruler-template');
this.createShadowRoot().appendChild(t.content);
}
}
});
document.registerElement('font-ruler', {prototype: proto});
— is appending the template content to your shadow root. You do not need to import node in the existing document (which seems to cheat Chrome and force it to apply light styles... uhm... well... somewhen.)
<font-ruler></font-ruler>
— in HTML is absolutely the same as
var font_ruler = document.createElement('font-ruler');
document.body.appendChild(font_ruler);
so I tried to keep everything as clear as possible. Hope it helps.
Use the CSS all property, it is a replacement for resetStyleInheritance

How to know that which js file or function is applying inline css into my element

I have inline css in my element which i do not want. There is a lot of js in my website and i do not know from where this css is coming.
Any help will be great.
Thanks in advance.
If I were you, I'd use removeAtrr() to remove all the inline style for that element:
$('#yourElementId').removeAttr("style");
After that, I'll set any style again through external css file or javascript if necessary.
Or if you want to override the inline styles, you can also try to use !important attribute in css.
I think the most solid way to do it would be to use the browser's dev tools to run through the js one line at a time. This will show you the exact point in the code execution where the style is added. Here's a link demonstrating how to use breakpoints: https://developers.google.com/chrome-developer-tools/docs/javascript-debugging#breakpoints
Otherwise, if you're confident the code will be jQuery functions, do a search for .css(. If it's possible the change is made without jQuery, search for .style.. Some other possibilities are fadeIn, fadeOut, and animate. Once you find any of these, you can track what element they are being applied to to determine if they are relevant to the element you want to change.
Here are some selectors to look out for (vanilla JS and jQuery)
ClassName
document.getElementsByClassName('some-class');
$('.some-class');
ID
document.getElementById('some-id');
$('#some-id');
TagName
document.getElementsByTagName('tagNameHere');
$('tagNameHere');
QuerySelector
document.querySelector('cssSelectorHere');
document.querySelectorAll('cssSelectorHere');
$('cssSelectorHere');
If the problematic CSS is set with jQuery, you can hook into jQuery's cssHooks API to see when a particular CSS is being set. For example, if the problematic CSS is "margin-right" you can detect when it is being set and throw an exception so you can trace it through the browser's debugger:
var targetElement = document.getElement("checkme");
$(function() {
$.cssHooks["marginRight"] = {
set: function(node, value) {
if(node == targetElement) {
throw "stop that!";
}
else node.style.marginRight = value;
}
};
});

JavaScript setting pointer-events

I am trying to set pointer-events: none for a div through JavaScript, however the property is not being applied.
I have tried:
document.getElementById("div").setAttribute("pointer-events", "none");
And:
document.getElementById("div").style.pointer-events = "none";
But neither worked, any ideas?
Your first attempt failed because it was a CSS property and not an attribute (part of the style attribute).
Your second attempt failed because for some off reason, when making this API casing-like-this gets converted to camelCasingLikeThis . This is likely because the folks who built JavaScript and the folks who built CSS weren't very well coordinated.
The following should work:
document.getElementById("div").style.pointerEvents = "none";
You can access style properties via Bracket notation like this:
document.getElementById("div").style['pointer-events'] = 'auto';
No need in camel case modification in this case.
There is an example in a book which uses element.setAttributeNS(null, "pointer-events", "none"); instead of using element.style.pointer-events = "none";.

In firefox, how can I change an existing CSS rule

In firefox, I have the following fragment in my .css file
tree (negative){ font-size: 120%; color: green;}
Using javascript, how do I change the rule, to set the color to red?
NOTE:
I do not want to change the element.
I want to change the rule.
Please do not answer with something like
...
element.style.color = 'red';
What you're looking for is the document.styleSheets property, through which you can access your css rules and manipulate them. Most browsers have this property, however the interface is slightly different for IE.
For example, try pasting the following in FF for this page and pressing enter:
javascript:alert(document.styleSheets[0].cssRules[1].cssText)
For me that yields the string "body { line-height: 1; }". There are methods/properties that allow you to manipulate the rules.
Here's a library that abstracts this interface for you (cross-browser): http://code.google.com/p/sheetup/
function changeCSSRule (stylesheetID, selectorName, replacementRules) {
var i, theStylesheet = document.getElementById(stylesheetID).sheet,
thecss = (theStylesheet.cssRules) ? theStylesheet.cssRules : theStylesheet.rules;
for(i=0; i < thecss.length; i++){
if(thecss[i].selectorText == selectorName) {
thecss[i].style.cssText = replacementRules;
}
}
};
You can change CSS rules in style sheets through the CSS Object Model (currently known as DOM Level 2 Style). However, if you literally have "tree (negative)" in your style sheet that rule will be dropped and not appear in the Object Model at all.
As there is no HTML element tree I am going to assume that tree is the id or class of another element.
You would first retrieve the DOM element by id:
var tree = document.getElementById("tree");
Now tree represents your DOM element and you can manipulate it any way you like:
tree.style.color = "red";
Here is a great reference for mapping css properties to their javascript equivalent.
I'm not sure you can do actual class/selector overrides. You would need to target each element that used the .tree class and set the CSS. The quickest and easiest way would be through jQuery (or another similar framework):
$('.tree').each(function() { this.style.color = "red"; });
You could even use the built-in CSS functions:
$('.tree').css('color', 'red');
(I did it the first way to show you how standard JS would do it. The $(...) part is jQuery for selecting all elements with the .tree class. If you're not using jQuery, you'd need alternative code.)
If tree is an ID, not a class (there should only be one on the page) so using getElementById should be fine. Your code should look like the other answer.
for( var i in document.getElementsByTagName("tree") ){
document.getElementsByTagName("tree")[i].style.color = "red";
}
As I said in another answer's comment, I've never seen this done how you want. I've only ever targeted elements the same way as the CSS renderer would and changed each element style.
I did see this though: jQuery.Rule
It sounds like it does what you want but the demo causes my browser to flip out a bit. I'd invite you to look at the source to see it really does do what you want, and if you want to use it without jQ, use it as a starting point.
Edit: yes this should work. It works by appending another <style> tag to the page and writing out your overrides within. It's fairly simple to follow if you wanted to port it to plain JS.
For debugging, you can use Firebug to change the CSS rules on-the-fly.
If you want to change the rendered css rules from one page request to the next then some sort of server-side scripting will be required. Otherwise the original style sheet would simply reload at the next page request.
If you want to use an event on the first page to force the server-side action then you can use AJAX to actually change the CSS rule for the user.
"I want to change the rule so that
when I navigate to the next page, I
don't have to make all the changes
again."
It sounds like what you might want then is a remote request ("ajax") back to the server with the request you want to make, and generate a dynamic stylesheet which is sent back to the client?
How/why is this Firefox specific?
I want to change the rule so that when I navigate to the next page, I don't have to make all the changes again.
There are two approaches I can think of here. Namely client side and/or server side.
Client side:
Store the theme setting into cookies and load them up next time by javascript.
Server side:
If your site have an login system, you may also store the user preference into the database and generate the webpages with this inforamtion in mind next time on.
Utimately, you are still writing things like element.style.color =. But, they should get what you want.

Categories

Resources