How to reset the style properties to their CSS defaults in javascript? - javascript

On a php generated page there are several elements like this:
<td class="defaultTDStyle" style="color:userDefinedCustomColor" id="myTDId"></td>
So there is a default style and I apply several extra styles that override the style defined in the CSS.
Is there a way to remove these added styles from javascript?
It seems the obj.style.color="default" and obj.style.color="auto" don't work. How can I reset the color to the CSS default from javascript?

If recollection serves, obj.style.color="" should work... I don't know if it's right though.

Set the style property values to the empty string:
obj.style.color = "";

The new way:
el.attributeStyleMap.delete('color')
or clear everything:
el.attributeStyleMap.clear()
Not all browsers support this yet though. See StylePropertyMap on MDN for more details and browser compatibility.
See also CSS Typed Object Model and Working with the new CSS Typed Object Model.

You could save the attribute style before overriding it, and then apply it again. Like this:
// Get element styling
const element = document.getElementById('someId');
const style = element.getAttribute('style');
const classList = element.classList;
/** Code for overriding element styling goes here **/
// Retrieve original styling
const newClassList = element.classList;
for (let item of newClassList)
element.classList.remove(item);
for (let item of classList)
element.classList.add(item);
element.setAttribute('style', style);

Related

The margins in div of new tab not at all taking effect

Hi I am creating dynamic form in new tab using JavaScript. Margin effects on div are not taking effect. I am neither able to set the margins using class and id in css nor using div.setAttribute. Below is the code.
`
var openWindow = window.open('dynForm.html','_blank','');
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var div=document.createElement("div");
div.setAttribute("style","border:solid");
div.setAttribute("style","margin-left:1cm");
div.setAttribute("style","margin-right:1cm");
div.setAttribute("style","margin-bottom:1cm");
div.setAttribute("style","margin-top:1cm");
div.setAttribute("style","background-color:lightblue");
`Only background color is taking effect on the new tab. The below screen shot shows how the screen looks irrespective of the values of margin.
Quesstion 2: No class or id attribute in my css is being applied to div.
#myDIV2{
background-color:lightblue;
}
I tried div.id="myDIV2";
I also tried div.setAttribute("id","myDIV2");` I applied the same using class also, but still couldn't find any difference. I do not know why its not working and what went wrong here. Please help
You're overriding the styles every time you call setAttribute, try combining the styles and then set the style attribute only once:
var openWindow = window.open('dynForm.html','_blank','');
var styles= [
"border:solid;",
"margin: 1cm;",
"background-color:lightblue;"
];
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var end_styles = "";
for (var i=0; i<styles.length;i++) {
end_styles += styles[i];
}
var div=document.createElement("div");
div.setAttribute("style", end_styles);
Note: the fiddle won't work on stackoverflow, I used it because it's easier to format code
This is happening because your all style attribute are getting overridden by previous div.setAttribute and your last attribute div.setAttribute("style","background-color:lightblue"); getting applied. Try to put all styles in one go. div.setAttribute("style","style1:value1;style2:value2;style3:value3;");

Chrome not handling .style = "background-color:#333223;"

In the code included below, the script is toggling a div on and off. The .style
code, controls the background color of the the parent element of the div being toggled
on and off. The code works in Opera but not in Chrome, and I haven't been able to
research (search) a solution.
I can of course move on and write other code and achieve what I need, but this has my
curiosity up now.
function CheckOutOpn(){
var Inny = document.getElementById("RightPaneASxOrderForm");
MVxCheckOutForm();
CDxButtonOpnChkOut();
MVxCLOSExBttnChkout();
Inny.style = "background-color:#332223;";
}
function CLOSExCheckOut(){
var Inny = document.getElementById("RightPaneASxOrderForm");
MVxButtonOpnChkOut();
CDxCLOSExBttnChkout();
CDxOrderFormItself();
Inny.style = "background-color:#33B32E;";
}
I think you should be using:
Inny.style.backgroundColor = "#332223";
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style
... Except in Opera, styles can not be set by assigning a string to the
(read only) style property, as in elt.style = "color: blue;". This is
because the style attribute returns a CSSStyleDeclaration object.
If you want to set the style of an element textually, you need to use either
Inny.style.cssText="background-color:#33B32E"
or
Inny.setAttribute("style","background-color:#33B32E")
or you can set the properties directly:
Inny.style.backgroundColor = "#33B32E";
I think this will work for you fine. only mistake you are doing is, when you are adding the css properties to the element.
function CheckOutOpn(){
var Inny = document.getElementById("RightPaneASxOrderForm");
MVxCheckOutForm();
CDxButtonOpnChkOut();
MVxCLOSExBttnChkout();
Inny.style.backgroundColor = "#332223";
}

Dynamically apply CSS filter

How to dynamically apply CSS filters? I have tried the following for Chrome.
image.style = "-webkit-filter: brightness(50%);";
You should set value to the webkitFilter property, not to the style object. This syntax will work:
image.style.webkitFilter = "brightness(50%)";
If you don't know JavaScript property name, you can reference it by CSS property (like karaxuna suggested, will work too):
image.style["-webkit-filter"] = "brightness(50%)";
image.style["-webkit-filter"] = "brightness(50%)";
Add that filter to a class:
.bright {
-webkit-filter: brightness(50%);
}
And toggle that class:
image.classList.toggle('bright');
1) Check if browser supports css-filters (if needed)
2) Detect if "filter" property needs vendor in current browser and save it
3) Set filter value in format:
el.style["-vendor-filter"] = value;
or
el.style.vendorFilter = value;
Check small demo for it: http://codepen.io/malyw/pen/EDnmt
Also you can find large demo showing css filters in action: http://malyw.github.io/css-filters/

How to dynamically set and modify CSS in JavaScript?

I have some JavaScript code that creates some div elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css file, I would like to set the CSS className of my element and then dynamically inject some values into the defined CSS property.
Here is what I would like to do :
style.css:
.myClass {
width: $insertedFromJS
}
script.js:
var myElement = document.createElement("div");
myElement.className = "myClass";
I want to do something like this but at that point myElement.style.width is empty
myElement.style.width.replaceAll("$insertedFromJS", "400px");
I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.
If I understand your question properly, it sounds like you're trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can't do that in the way you're trying to do it. In order to do that, you'd have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that's a really overly-complicated way to go about doing something that...
myElement.style.width = "400px";
...can do for you in a couple of seconds. I know it doesn't really address the issue of decoupling css from js, but there's not really a whole lot you can do about that. You're trying to set css dynamically, after all.
Depending on what you're trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.
Setting the style, might be accomplished defining the inner-page style declaration.
Here is what i mean
var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.
if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules) // Standards Compliant {
csses = document.styleSheets[0].cssRules;
}
else {
csses = document.styleSheets[0].rules; // IE
}
for (i=0;i<csses.length;i++) {
if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
{
thecss[i].style.cssText="color:#000";
}
}
could you use jQuery on this? You could use
$(".class").css("property", val); /* or use the .width property */
There is a jQuery plugin called jQuery Rule,
http://flesler.blogspot.com/2007/11/jqueryrule.html
I tried it to dynamically set some div sizes of a board game. It works in FireFox, not in Chrome. I didn't try IE9.

changing css class model using JavaScript

Is it in any way possible, to change a css class model using JavaScript?
Pseudo code:
function updateClass(className, newData) {
cssInterface.alterClass(className, newData);
}
className being the name of the class, which is supposed to be changed (like ".footer") and newData being the new class content (like border: "1px solid pink;").
The target is, actually, just to save space: I am working with CSS3-animations, so changing one attribute of an element, which is affected by it's class, will terminate the animation of of it - The (in my case) font size won't change anymore. Using different classes will require an entire new set of classes for all affected elements, I'd like to avoid this.
I am not searching for a change via
element.className = "foo";
or
element.style.fontSize = "15pt";
Thanks for your help, guys :)
Here's my function to do this...
function changeCSS(typeAndClass, newRule, newValue) // modify the site CSS (if requred during scaling for smaller screen sizes)
{
var thisCSS=document.styleSheets[0] // get the CSS for the site as an array
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules // work out if the browser uses cssRules or not
for (i=0; i<ruleSearch.length; i++) // for every element in the CSS array
{
if(ruleSearch[i].selectorText==typeAndClass) // find the element that matches the type and class we are looking for
{
var target=ruleSearch[i] // create a variable to hold the specific CSS element
var typeExists = 1;
break; // and stop the loop
}
}
if (typeExists)
{
target.style[newRule] = newValue; // modify the desired class (typeAndClass) element (newRule) with its new value (newValue).
}
else
{
alert(typeAndClass + " does not exist.");
}
}
Called with (example)
changeCSS("div.headerfixed","-moz-transform-origin", "100% 0%");
hope this helps.
See my answer here. To answer your question: Yes, it's possible.
#CSS3: I tried exactly the same in one of my html5 experiments. I created an extra <style> element, and changed its contentText to the CSS class definitions I needed. Of course changing the cssRule object would be much cleaner :-)
As far as I can tell the CSS object model cannot easily tell you whether you already have an existing style rule for a particular class, but you can easily append a new rule for that class and it will override any previous declaration of that style.
I found an example of creating dynamic stylesheets.
You should take a look at dojo, it has some nice features where you can do just that..
require(["dojo/dom-class"], function(domClass){
// Add a class to some node:
domClass.add("someNode", "anewClass");
});
http://dojotoolkit.org/reference-guide/1.7/dojo/addClass.html

Categories

Resources