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.
Related
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');
This is more of an organisation question concerning Jquery.
Using the following simple example:
click me
<script>
$(document).ready(function(){
$('.click').on('click',function(){
alert('Clicked!');
});
});
</script>
Now multiply this by a 1000 on your website, it can quickly get messy. You also can forget which classes you attributed for Jquery or for your CSS.
I usually try to avoid mixing both, so I add my classes for CSS and others for the Jquery, in case I change I the layout or use that section somewhere else, ... I can change the CSS. But how to do you remember which one is for CSS or Jquery? Do you name your classes "JSclassName" or something like that?
Let me know if I'm not clear and thanks for your help.
Have a consistent naming scheme for your "sections" in terms of case and meaning
Keep id and class names the same both for CSS and JS to avoid the confusion.
Relating to semantic code, you should give meaning to the class/id names as well. This helps you remember what you are adding code for. Don't use something like "centeredContainer" or "thisIsClickable".
Example:
<section class="weatherWidget">
<ul class="forecast">
<li class="vicinity">
...
<ul class="news">
<li class="region">
...
I also namespace my CSS and JS to avoid conflicts. The following code ensures that only weather widget contents are referenced by the code:
//this click event is only for weatherWidget vicinity
$('.weatherWidget .vicinity').on('click',function{...});
//this CSS is only for weatherWidget regions
.weatherWidget .region{...}
Also, although I don't really use them nor endorse using them, LESS and SASS frameworks can also help in terms of avoiding redundant CSS code by using variables.
First, give your identifiers more meaningful names. In my opinion, click is not a ideal one. A button is clickable, so is a anchor, even a div element.
Second, if you do have hundreds of identifiers, try to use namespace to distinguish CSS/JavaScript identifiers. But I think this is not necessary, using the CSS identifier in your JavaScript is natural, a meaningful name is in the first position.
<style>
.ui-cart-button{ };
</style>
Buy
Namespace is a good way to make your code cleaner and more readable, I recommend you to have a look at the source code of jQueryUI.
Here are my suggestions;
Always use unique IDs. IDs should be unique, given to a specific element or selector only while classes can be given to multiple selectors.
No need to use same class for JavaScript and CSS both since multiple classes can be assigned to a selector like <div class="class1 class2">
Use a style-sheet attachment for common items appear in multiple pages so as to limit Embedded and Inline styles.
Links below will suggest some guidelines for you.
30 CSS Best Practices for Beginners
15 Best CSS Practices to Make Your Life Easier
10 Best CSS Practices to Improve Your Code
All the above given information is to let you know about using CSS. From all these info, you may formulate the best option ideal for your needs.
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/
I often use CSS ids or classes to select elements in Javascript. Many of those classes do just exist for that use case and do not have any styles attached at all.
I ponder now if it would be any good to mark those classes explicitly. Maybe something like a leading underscore (e.g. class="_field").
The thing is that I never heard of such a practice. Is this recommended? Maybe already used in a bigger project? What kind of marking would make sense? I read somewhere that a leading underscore could be problematic. What else could I use to easily identify those "Javascript only" classes?
You can do that as a personal coding convention. The spec doesn't state that the class attribute must be used in styling only, or in scripting only. You can use it to classify your elements in any way you want, so there's no restriction in how you name and organize your classes.
The majority of the time I find that the class names used in JS matches the styling I want to do in CSS. As long as you name them properly it's not a big deal that a class name is used by only CSS or JS.
You may want to use the data-* attributes suggested by HTML5. They even work in HTML4, though the resulting code is not valid.
As a sidenote, ExtJS has used "namespaced" custom attributes for their tree nodes for quite some time:
<div class="x-tree-node-el x-tree-node-leaf x-unselectable cls"
ext:tree-node-id="Foobar">
(They should change that to data-ext-tree-node-id btw)
It is better to use ids for working with JavaScript since an element has only one id that is unique to it, while classes can be applied to multiple HTML elements.
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.