Changing CSS with JavaScript - javascript

When using JavaScript to change the CSS does the JavaScript simply make new inline-CSS which takes presidents? I've always felt inline CSS is trashy and was wondering if there's a better way?
For example if you have
<div id="author">Author's name</div> which is normally coloured green from a reference to an external CSS and you want to change it to red must you use
document.getElementById('author').style.color='#FF0000'
Must changes to appearance be done using inline-stying?

No, you're not modifiying the CSS. You're just setting style properties. The mark up of an element is decided by three things: CSS, style and inline properties like width="100". The order in which they are applied can get a little fuzzy.
style does always overrule CSS though, unless you're using !important.
A more common way to change the mark up of elements is to add and remove classes. This allows you to keep all your style definitions in your CSS file and makes your code considerably less complex.
You could do:
document.getElementById('author').className = "selected";
to add a class to it and have it be display in a different mark up.
If you're using jQuery you can use addClass and removeClass. Under the hood this just modifies the className property. It's easy enough to write your own implementation, you just need to do some string juggling.

There is more than one way to change the styling of an HTML element. If using jQuery, for instance, you can add/remove class names to elements easily, like so:
$("div").addClass("className");

It is always cleaner to define all your styles in classes so you can change the whole application look and feel easily instead of using inline styles.
the easiest way to do so is to define a CSS class
.reddiv {color: #FF0000}
then you can easily change the color of the div to red using jquery
$('#author').addClass('reddiv');

Related

Use part of class name as a css variable

I'm using css to change the sizes of two divs so that their size represents some value that changes a few times per session.
Is there anyway to define a css class something like:
.shiftydiv(*) {
width:\1;
}
where \1 is whatever * matched? Then I can just add a class like .shiftydiv25 via jquery whenever I need to change the size.
I don't need legacy support for browsers and I'd prefer not adding any dependencies.
If I can't do it with pure css I'll either create CSS classes dynamically or inject style= attributes into my code. Which would be better (less bad).
EDIT:
If there is a nice way to do this with JS/jquery that would work well too.
EDIT 2:
So doing this with js is actually quite easy. oops
Maybe instead pure CSS use SASS/LESS and generate multiple classes?
You can use for loop and iterate over lets say 20 elements and make .shiftydiv1, shiftydiv2, ... shiftydiv20.

Is the only way to change a style to do it per-element in JavaScript?

I've been looking at a few different things I'd like to using JavaScript to tweak styles globally. I'd like to do this by changing the CSS rule that dictates the element's style (akin to doing this through the Inspector in Webkit), but after coming to https://developer.mozilla.org/en/DOM/CSSStyleRule I now don't know if this is even possible:
style
Returns the CSSStyleDeclaration object for the rule. Read only.
So, is there no way to change higher-level styles in JavaScript?
To modify your existing styles, either find the stylesheet in document.styleSheets or from the the .sheet property of the <style> or <link> element you want to modify. Then modify the properties in whatever rule they're located in (see https://developer.mozilla.org/en/DOM/CSSRuleList). I'd advice against using the CSSOM to modify properties, as browser support for modifying CSS properties through the CSSOM is pitiful (no browsers whatsoever support it). Instead, just set a string value.
If all you want to do is insert a new rule, just get a stylesheet from the method above, or document.documentElement.appendChild(document.createElementNS("http://www.w3.org/1999/xhtml","style")).sheet. Then use insertRule to add your rule.
CSS Styles can be created/changed programmatically via javascript, but that is not usually the easiest way to solve a problem because different browsers do it differently so cross-browser support is a bit of a pain unless you already have a library that abstracts that. You can see generally how to do it here: http://www.quirksmode.org/dom/changess.html.
If the styles you want to switch between are known in advance, then the easiest way to change between them is to define both those styles in a stylesheet, and use different class designations to trigger one vs. the other.
If you are just trying to affect one object or a small number of objects, you can simply add or remove a class name via javascript on the affected objects.
If there are large numbers of objects, then something I've done is to add a class name on the body tag to trigger the alternate style to take effect for all affected objects. It works like this:
Lots of these in your HTML:
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
Then, have two pre-defined CSS rules like this in this order:
.foo {background-color: #777;}
.alternate .foo {background-color: #F00;}
Then, using Javascript, any time you want to change to the alternate style, you simply do this (using jQuery or any favorite class library):
$(document.body).addClass("alternate");
To go back to the original style, you can just remove that class:
$(document.body).removeClass("alternate");
This doesn't have to be added to the body tag - it can be added to any common parent of all the affected objects.
I personally find this a lot simpler than programmatically creating style rules and it keeps the actual style information out of the code (where designer people who aren't programmers can more easily access it).
You can see this technique in action here: http://jsfiddle.net/jfriend00/UXKvg/

Applying CSS to dynamically named elements

I wrote a theme for Google+. It injects CSS/Javascript to replace some colors, background images, etc. They recently seem to have renamed a lot (most) of their classes and ID's. If I were to rewrite the code, is there a way to assign CSS (through javascript, presumably, like jquery's .css() function) to page elements with dynamic names?
EDIT: If so, how?
Code: https://github.com/bichiliad/G-Theme
Example: I used this to replace the logo:
$(".a-U-Pg-T img:first").attr('src', logoURL);
However, with the new update, the div enclosing the logo is now ".a-fa-bh-T".
You could use jQuery find() and regex patterns to try to find the elements themselves based on their hierarchy, but if the hierarchy changes then that won't work either. And yes, you could use jQuery's css() to apply those styles.

Overriding containers CSS behavior

I have created a Javascript based element that can be embedded into websites. The Javascript itself adds the HTML code into a pre-defined HTML container and dynamically loads the necessary CSS file that contain the element's visual definitions.
The problem starts when the site itself has its own definitions for general items. For example: The site's CSS defines a certain list style which is applied on the element's list because the element's CSS doesn't define an explicit list style or if the site's CSS overrides the element's CSS definition.
For the time being, I was able to solve this specific issue by explicitly defining the list's style and adding the !important definition. However, I would definitely want to go for a more robust solution that will assure that:
1. CSS definitions from the site's CSS that are not explicitly defined in the element's CSS will not be applied on the element
2. I will not need to explicitly add the !important definition to every one of my CSS definitions
Is there a general way in which I can specify that a site's CSS will not be applied on a certain element or that only a certain CSS will be applied to a specific element?
Any help will be greatly appreciated.
You need to use a localised reset.
Grab an existing CSS reset, such as Eric Meyer's Reset Reloaded and namespace all the selectors with your parent element, e.g. #something a { ... }.
I was going to put up the same answer as Alex, but he beat me - but I was also going to add:
If you're not going to use #alex's suggestion then ultimately you have to explicitly style all of your elements the way that you want them to appear; using selectors that keep your styles local too (and don't interfere with the parent site) - in the same way that the localised reset is suggested.
Update
Or you could do what Google Translate and many other widget-type things do, usually a no-no but in dynamic scenarios I think perfectly acceptable; since the visual style of your elements is not just important to you but to the container site: use inline styles.
Final update
So I thought I'd just double check what Google Translate does. And of course it's an iFrame inject in addition to using inline styles. They no doubt use inline styles to maximise compatibility and so that the browser doesn't have to make another request to get the stylesheet; and they would be using an iFrame so they can ensure a consistent look and feel.
Consider both of those points in tandem - and weigh that up against the amount of work that might be required in resettting all the styles for a minority portion of the page; or defining rules for every CSS property you need to control - which, let's face it, is basically all visual CSS properties.
The iFrame solution actually seems to offer the best solution - if you can use it; hence I've +1'd the first comment by #roberkules on your question.

What is "CSS on-the-fly"?

What is CSS on-the-fly?
Does JavaScript allow to modify CSS on-the-fly?
Changing an Elements CSS Attributes
The easiest way to modify CSS on the fly is probably with Jquery:
$('#elementID').css("height", "300px");
First parameter is the CSS attribute, second is the new value.
Try and steer away from over using this, as it wont degrade nicely probably for people without Javascript enabled.
Changing CSS Classes
Related info: How can I change the css class rules using jQuery?
This afaik is not possible on the fly, see above link.
You can also use .style to access css styles in javascript eg
document.getElementById("anElement").style.width = "300px";
Though I think this might only affect single elements
Yes. It does allow you to modify the CSS on the fly.

Categories

Resources