Modifying CSS properties associated to a given CSS class using JavaScript - javascript

I have a JavaScript color picker linked to a text input. I would like several colored elements on my to change their color on the update of that color input. I could create several classes, one for each color (blue, red, green, etc), but i would like to have the whole 24 bits coloe palette, not just a few of them.
Is it possible to modify the value of the properties associated to a given CSS class ? If yes, will modifying these values apply new values on the rendered page in real time ?
Thanks in advance :)

Totally possible, and yes it will be updated in real time.
Here is a function to do the class property update, tied to a mouseover event (requires jQuery 1.0+). Mousing over div with id myDiv will update the CSS background color to white for all div's with class myColorDivs:
$('#myDiv').mouseover(function() {
$('.myColorDivs').css('background', '#fff');
});

Sorry, i'm late ...
Had the same question some days before and didn't find a practical answer.
Here's how I solved it for me (requires jquery):
Add an inline-stylesheet after all other stylesheets your page may need with the class you want to change.
Assign a TITLE Attribute to this stylesheet!
<style title="tomrulez" type="text/css">
/*the stylesheet to change - Note the TITLE*/
.shaded{
color:green;
}
</style>
Add this function:
function modCSS (stylesheet, rule, attrib, newval){
$.each( document.styleSheets, function( skey, svalue ) {
if(svalue.title==stylesheet){
$.each(svalue.cssRules,function (rkey,rvalue){
if (rvalue.selectorText==rule){
rvalue.style[attrib]=newval;
}
});
}
});
}
call it like this:
<div onclick="modCSS('tomrulez','.shaded','color','red')"> click here</div>
Parameters are:
stylesheet -> the TITLE of the last stylesheet on your page
rule -> The CSS-rule you want to change
attrib -> The attribute of the rule you want the change
newval -> The new value you want to assign to that attribute
I've tested this with Firefox, Chrome and IE10.
IE may not work in older Versions. But I develop mainly backends for a small group of users that do not use IE if i tell them (Yep, i'm a lucky about that!)
Btw. Here is a Plunker that works for me: http://plnkr.co/edit/EMDpjU06U2p83Df8Lolq?p=preview

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>

Modifying :hover styling for an element with jQuery/javascript

I am building a WYSIWYG page styling editor with jquery/javascript. I'm trying to provide a way to modify the :hover state of links so my users can change the color, size, weight, etc of links. I know how to apply styling to elements for their default state, but can't find any documentation on how to apply styling to an element :hover state.
Any help out there?
To currently apply anything I am doing the following:
$('#content a').css('color','#ffcc00');
I need to do something similar for a:hover. ie:
$('#content a:hover').css('color','#000');
If you want to make the change using javascript you can attach it to jQuery.hover().
Here's a full working example
$('a.link').hover(
function(){
$(this).css('color',$('input').val());
}
);
I built a WYSIWYG editor and I store the user defined settings in a db so instead of reloading the page after I save their change to the form I update the behavior with javascript.
you can use css like assert your element´s id is
"element1"
css :
#element1:hover {
background-color:pink;
}

CKEditor plugin to set classes

What I want to do is something similar to the native foreground / background colors dialog. The difference is, it will have buttons with colors directly in a toolbar. So one plugin has to have multiple buttons, with different styles (colors). The other problem is, that this native plugin sets CSS color and background-color properties. I need to use classes instead, like this:
text <span class="fg red">colored text</span> text
and
text <span class="bg blue">colored background</span> text
Clicking into colors have to change color of a span with fg class (and background colors - bg class)
How can I achieve this?
First of all you have to add your own buttons. Check source of any plugin that does this - e.g. basicstyles/plugin.js. You've got to create command for each button and then register all buttons. Simple.
Then I propose to use our styles implementation. It allows to apply/remove defined style from the given selection/range. In the style definition you can specify that it will apply span element with given classes. Check this style definition.
And the last step - join these things together. Command associated with button should apply/remove this style. There's ready to use one - check CKEDITOR.styleCommand usage here.
Everything you need is in basicstyles plugin, so just refer there.
Pozdrawiam :)
If you're flexible about the interface, you could just add your styles to the "Styles" selector.
It would be less work than creating your own plugin. Especially if you're using CKEditor 3.6 or later where you could use the new Stylesheet Parser Plugin.
You're welcome to use the plugin from the answer where you asked me to look at this question.
It's based on the "basicstyles" plugin. If you look at the comments I included, you'll see that you can use it to add multiple buttons and multiple styles.
// This "addButtonCommand" function isn't needed, but
// would be useful if you want to add multiple buttons
You would have multiple calls to the addButtonCommand method.
addButtonCommand( 'Fg_red' , 'Label' , 'fg_red' , config.coreStyles_fg_red );
addButtonCommand( 'Bg_blue' , 'Label' , 'bg_blue' , config.coreStyles_bg_blue );
The last line of code after the plugin code is what you add to your configuration. You can use any attributes that you like:
CKEDITOR.config.coreStyles_fg_red = { element : 'span', attributes : { 'class': 'fg red' } };
CKEDITOR.config.coreStyles_bg_blue = { element : 'span', attributes : { 'class': 'bg blue' } };
You could also create a plugin based on the "colorbutton" plugin. It creates the native foreground / background colors dialog.

CSS gradient filter Javascript and IE 9

problem: IE9
I have a table. And i have a CSS class. The CSS class contains a gradient filter:
.red
{
filter:progid:DXImageTransform.Microsoft.Gradient(sProperties);
}
if i do:
... <tr class="red"> ...
everthing works fine. If i do
<script type="javascript">
... element.className = 'red';
</script>
the filter doesnt apply. does anybody knows what event could be fired after assignment to apply? Doing td class="red" is no solution, the table is rendered with a powershell table helper. jQuery or other frameworks are also no solution, it would blow up this simple "one page" application. Thanks in advance, Robert
Edit:
http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx
object.style.filter = "progid:DXImageTransform.Microsoft.Gradient(sProperties)"
Assuming element actually refers to the element you want to make red, and that the script calling it is called after element actually exists on the page, and that your CSS includes actual arguments to Gradient and not just the literal sProperties, then try zooming the page in and out to manually force a redraw. Assuming the gradient suddenly appears, try toggling the display of the element to hide and then show it again, thus forcing an automatic redraw.
Actually, that's a lot of assumptions... Maybe you should just use a background-image instead?

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