I want to loop and add several multicolored spans to a div container. To do this efficiently, I simply alter the css, instead of adding a new color class to the element:
var colorEn = ["RoyalBlue", "LawnGreen", "red", "orange", "yellow", "black", "white", "MediumOrchid"];
for ( i = 0; i < colorEn.length; i++ ) {
var $span = $('<span />').attr('class', 'coloratorSquare');
$span.css({background : colorEn[i]});
$("#colorator").append($span);
}
Generating, for example:
<span class="coloratorSquare active" style="background: rgb(65, 105, 225);"></span>
Then, when I select (click) a certain span, it will change color to Silver show it has been selected, and set all other sibling spans back to their original colors. Here's a snippet:
$(this).addClass("active").siblings().removeClass("active");
The problem is, if I alter the css of the span elements ($span.css(...)), it doesn't apply the CSS changes on add/remove class. But if I comment out changing the css of the span, the multiple colors aren't added, but the active class add/removal of selected/deselected span changes colors as expected:
// $span.css({background : colorEn[i]});
CSS:
.active {
background-color: Silver;
color: black;
}
I would simply not alter .css of a span at all, but don't think it makes sense to add classes to each span during generation, and have to add CSS class rules for each color to replicate that .css functionality.
My question: How can I add multiple different css rules (ex: multicolors) to randomly generated elements without a) having to generate all those rules manually in the CSS file, and b) altering the .css with jQuery such that it causes problems with adding/removing CSS class rules.
Sorry if this is unclear.
Thanks!
You could use !important on the silver color to have it override the locally set attributes of your elements, but that technique is frowned upon.
My recommendation is to consider the circumstances; if this is not throwaway code, then it usually makes better sense to set classes on the elements instead of directly manipulating their style attribute. If it's something you need for a mockup then by all means slap !important on it and move on.
Related
All:
I used D3 to add style to SVG element like:
svg.append("rect")
.attr("id", "testclass")
.classed("hascolor", true)
.style("fill", "red");
Then I define another class:
.nocolor{
fill: transparent;
}
And when I want to apply this class to change style like:
svg.select("#testclass")
.classed("nocolor", true);
The class of RECT changed, but the style did not apply( it only works when I use JS to change the style directly). I wonder if anyone could help with this to enable style changing by class on it?
Thanks
The inline styles has priority over the css style.
(I know that maybe this exact portion of code is not going to work in your case but is just for demonstrative proposes).
Here is a Jquery example, that you can test the style priority over inline style, first class that apply a rule and second class that apply a rule with !important.
HTML:
<div id='theOne' style="color: green;" class="colorRed"> Something that needs to be colored </div>
CSS:
.colorRed {
color: red;
}
.colorBlack {
color: black!important;
}
Jquery:
$('#theOne').addClass('colorBlack');
Fiddle
So posibles solutions to your problem are:
1) Add the rule fill: transparent as 'style' attribute.
2) Use a css class instead of the attribute style in the first step.
3) Add !important to the css Rule.
The thing is that inline styles are more important than attributes from any selector, like from class you used, se even new class is applied, the inline style still exists thus is more important, however you can use !important rule which will override inline styling.
First things that came to mind:
.nocolor{
fill: transparent !important;
}
or
svg.select("#testclass").style("fill", "transparent");
I have set of 6 divs, and when I click on each of them, a certain div changes its innerHTML, like some kind of menu. When user hovers over those "buttons" (actually divs), they highlight with CSS's property :hover. There's also :active, when a user is clicking on a "button".
Since the "information" div changes when clicked, I'd like to have the current selected div constantly highlighted, in a whole different color than when on hover. So I used javascript for this. I call a function that changes background color of all of the "buttons" (so I don't have to "remember" which one was clicked), and then changes this div's backgroundColor to appropriate color.
However, now I lost my :hover and :active styles. How to handle this?
Here are code snippets as requested:
function ofarbajSveU999() {
document.getElementById("menubutton1").style.backgroundColor = "#999";
...
document.getElementById("menubutton6").style.backgroundColor = "#999";
}
function showMeaning() {
document.getElementById("information").innerHTML = meaning;
ofarbajSveU999();
document.getElementById("menubutton1").style.backgroundColor = "#ccc";
}
meaning is a string, menubuttonX are 6 div's that act like buttons.
#kotd .menubutton {
float: left;
background-color: #999;
width: 120px;
padding: 2px 0px;
cursor: pointer;
}
#kotd .menubutton:hover {
background-color: #aaa;
}
#kotd .menubutton:active {
background-color: #bbb;
}
instead of changing the color with javascript, use javascript to add and remove a class (for example .current) to the active "button" and then style the .current class accordingly in CSS. jQuery would be the most elegant solution to do that using the addClass(),removeClass() or toggleClass() functions.
To explain the idea a bit further:
When you click on a button, you add a class to its class attribute instead of adding inline style properties. This allows to style them via your CSS stylesheet.
In jQuery it is really easy. You can do something like this:
$(".menubutton").click(function () {
$(".menubutton").removeClass("current");
$(this).addClass("current");
});
Step-by-step:
you first look for all DOM elements with class menubutton by calling $(".menubutton"). Then by using .click() you trigger an event if one of the menubutton elements gets clicked. The function(){} includes the functions that get executed on click. First
$(".menubutton").removeClass("current");
again gets all objects with class menubutton and removes the class current from any of them that have it. Second
$(this).addClass("current");
adds class current ti "this" ... meaning the clicked object.
This will make the clicked object in the DOM look something like this:
<div class="menubutton current">
In your CSS you can now style the objects that has the additional current class:
.currnet {
background-color:blue;
color:white;
}
DEMO
In pure JavaScript this will be a bit more tricky. Maybe this thread can give you some more insight into that:
How to add/remove a class in JavaScript?
You should be using jquery's .hover() function extensively.
Check out http://api.jquery.com/hover/ & http://api.jquery.com/click/
The samples and you can easily do this.
To be exact, you should be using the following two built-in functions :
$(selector).hover(handlerIn, handlerOut);
$(selector).click(event);
Cheers
I want to add another class to a element, but some of those elements already have an existing class, however the class I am adding I want it to be the first class added in the class field and don't want to append it; because from what I know, in general, rules in the last listed class will overwrite rules in the former classes, correct!?
I know of a jquery method as below..
$("p").addClass("myClass");
However from what I understand this just appends the class and you can't choose where to put it.
Is there any way to do this easily or will I have to start removing classes and re-adding them?
Not sure if there is any need to do something like this, I personally like advice of #bwoebi just change specifity.
But still if you need it, this might help
HTML
<div class="second">Lorem text</div>
jQuery
var $div = $('div'),
classes = $div.attr('class');
$div.attr('class', 'first' + ' ' + classes);
You can put your variable which contains class's name in place of 'first'
Demo
You add multiple classes to an element by simply separating the classes using a space. For example:
<p class="key_paragraph dark no_border">Your text here</p>
<p class="key_paragraph dark">Your text here</p>
The order in which the classes are listed in the html attribute does not matter. What matters is the stylesheet.
In your stylesheet (css file), if you want any of the classes to override another you could change the order of the rules in the stylesheet. For example, if the class 'dark' has a border and the class 'no_border' does not, you must place 'no_border' after 'dark' in your stylesheet to ensure 'no_border' overrides 'dark' for the first paragraph. Like so:
.dark {
border: 2px solid red;
}
.no_border {
border: none;
}
Secondly, you could add specificity regardless of the order of the css rules. For example, combining classes to say 'if an element has the classes dark and red' is more specific than either of the two above rules. See here for more info on specificity. Thus, the following rule would ensure there is no border on elements with the classes 'dark' and 'no_border' regardless of the order in which they appear on the stlesheet:
.dark.no_border {
border: none;
}
.dark {
border: 2px solid red;
}
A third option is to use the css :not selector to target all elements with the class 'dark' that do not also have the class 'no_border'. Again, the order of rules in the stylesheet will not matter here. This is done as follows:
.no_border {
border: none;
}
.dark:not(.no_border) {
border: 2px solid red;
}
There are other ways to do this, but hopefully I have explained three easy ways in a manner you can understand. There is a more jquery-specific demo here (see the third example). Let me know if you have any questions.
Just for fun in case you wanted to add the new class at a specific index inside the current classes:
http://jsfiddle.net/ckzVk/
function addClassAtIndex(elementId,classNameToAdd,index){
var element = document.getElementById(elementId);
var elementClasses = element.className.split(" ");
elementClasses.splice(index,0,classNameToAdd);
var newClasses = elementClasses.join(" ");
element.className = newClasses;
}
To add class "man" to div:
<div id="stuff" class="cool bro sweet">The div.</div>
JS:
addClassAtIndex("stuff","man",1");
Result:
<div id="stuff" class="cool man bro sweet">The div.</div>
I'd like to apply a CSS to some linkbuttons on page load but one of them <a id="lb1">logoff</a> must keep its style, no hover nor other event must change its style.
The linkbuttons have no class and the css applied to all of them is done to tags, this way:
a
{
//style
}
a:hover
{
// style
}
Is it possible?
No, you can't.
You can use more specific selectors (or even inline CSS with the style attribute) so that they are less likely to be overridden accidentally.
You can use the (eugh) sledgehammer of !important so they will only be overridden by another !important rule.
There is no way to prevent them being overridden though.
Please please please please please avoid using !important whenever possible. You will run into SO many annoying problems and issues from using this. I consider it a very lazy hack.
What you want to do is append a class to the link that you don't want overwritten. Classes are given a higher priority than general selectors (such a, p, b). So if you append this class to the link, the CSS will override the default CSS you have set for a.
CSS:
a {
color: red;
}
a:hover {
color: blue;
}
.derp:hover { /*you can add everything you want to preserve here, essentially make it the same as the link css. you can also change it to #lbl:hover, although there's no good reason to be using an ID as a CSS selector*/
color: red;
}
HTML:
this will turn blue on hover
<a class="derp" href="#">this will stay red on hover</a>
Here's a fiddle to show you. The second link has a class appended that preserves the original style: http://jsfiddle.net/p6QWq/
Why not add a class to all the link buttons you want to change, and not add it to the one you don't want to change.
Then you can call:
$(".myClass").css("backgound-color", "blue");
This would change the background color for every element with a class of myClass to a blue background.
Or you could add a whole new class to the link buttons that have a class of myClass:
$(".myClass").addClass("myExtraClass");
This would then make the class attribute of your link button class="myclass myExtraClass"
Seeing your code posted makes it a little more clear on what you want to do. Try this:
a {
text-decoration: none;
color: orange;
}
a:hover {
text-decoration: underline;
color: blue;
}
This would apply a default style to all <a> elements. Now you could overwrite this default style by providing a specific style for the anchor with the id you gave above:
#lb1 {
color: black;
text-decoration: none;
}
#lb1:hover {
color: black;
text-decoration: none;
}
I mocked this up in a quick and dirty jsFiddle. See if this gives you the desired result. IDs take precedence over classes and default element styling. So if you have one that you want to keep the same, apply and ID and style the particular element accordingly. This would also help you by preventing you from having to apply a class to several elements. It's less coding to apply one ID than to apply twelve classes. (Just an exaggerated example. I don't know how many links you have.)
Hope this helps.
css is cascading by definition, so any style you apply to a tags will apply to this specific one, except if you overwrite it.
You'll have to either assign a class to all the other buttons or overwrite all the default properties for this specific button.
Also, do not forget the pseudo-classes :visited and :active.
You should use !important in your css like :
a {
/* style */
background: #FFF !important;
}
a:hover {
/* style */
background: #FFF !important;
}
You could always overwrite your css by simply creating another stylesheet and place it at the END of your stylesheet links in the head of your html.
<head>
<link rel="stylesheet" href="location/location/first_stylesheet.css">
<link rel="stylesheet" href="location/location/revised_stylesheet.css">
</head>
This is not the most productive method of overwriting your css however; one would be well advised to eliminate the necessity for this separate stylesheet by simply appending elements with a class attribute. The class attr will allow you to modify basic html elements, tags and overlay a final layer to "rule them all". Enjoy!
I'm looking for a way to change the CSS rules of my stylesheet imported in the document. So I have an external stylesheet and some class and div attributes inside. I want to change one of the rules with JavaScript or jQuery.
Here is an example :
.red{
color:red;
}
So the idea is to do something in JavaScript and the HTML knows that now the color is another color like this:
.red{
color:purple;
}
But I want to have this rule for every element that I add in the future by the way of append. So if I add a span with the CSS class .red, the text has to be purple and not red.
I hope I made it clear.
You can inject style declarations into the DOM.
$("head").append('<style>.red { color: purple }</style>');
You jQuery .css() method to do that.
$('.red').css('color', 'purple');
For multiple rules:
$('.red').css({
'color': 'purple',
'font-size': '20px'
});
When you add dynamic element in future to DOM by the way of append, just give those element some class or id and write CSS rules like above after appending them and they will applied for all dynamically created element.
Working sample
Note
Add dynamic rules is not a good solution in my point of view. Instead of the you can load some external CSS file.
But if you need something like dynamic rules add method then:
$('head').append(
$('<style/>', {
id: 'mystyle',
html: '.red {color: purple }'
})
);
And for future use:
$('#mystyle').append(' .someother { color: green; font-size: 13px } ');
Working sample
If you want to add a rule, instead of editing each element's style directly, you can use CSSStyleSheet.insertRule(). It takes two parameters: the rule as a string, and where to insert the rule.
Example from the above link:
// push a new rule onto the top of my stylesheet
myStyle.insertRule("#blanc { color: white }", 0);
In this case, myStyle is the .sheet member of a style element.
As far as I can tell, the style element must be inserted into the document before you can grab its sheet, and it can't be an external sheet. You can also grab a sheet from document.styleSheets, e.g.
var myStyle = document.styleSheets[1]; // Must not be a linked sheet.
myStyle.insertRule("#blanc { color: white }", 0);
Note: The page recommends modifying elements by changing their classes, instead of modifying the rules.