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

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";
}

Related

addClass(); jQuery Function Not Working in Firefox

I have a script that picks a random background image for the body element of my document from a directory called bg-images. If the chosen background image has "_dark" in the image file name, I would like to add a special class to the body element.
Here is the jQuery I'm using. It works great in Chrome & Safari, but does nothing in Firefox:
var backgroundImage = $('body').css('background');
var isitdark = "_dark";
if (backgroundImage.indexOf( isitdark ) != -1 ) {
$('body').addClass("dark");
} else {
$('body').removeClass("dark");
}
How come this doesn't do anything in Firefox? Is there a better way of writing it?
I've tried adding "type=text/javascript" to all my script tags but that doesn't seem to help and the rest of the jQuery on my site works correctly in all browsers.
You're not getting the background image with $('body').css('background'); Use .css('background-image')
var backgroundImage = $('body').css('background-image');
It's not necessary because the string _dark will or will not be there but if you want to you can remove the url() or url("")
var backgroundImage = /url\(\s*(['"]?)(.*?)\1\s*\)/g.exec($('body').css('background-image'))[2];
Works fine in FF
http://jsfiddle.net/mNX3A/
background is a shorthand property. Shorthand properties are not guaranteed to be retrieved correctly with css:
Retrieval of shorthand CSS properties (e.g., margin, background, border), although functional with some browsers, is not guaranteed.
If you specifically want to get background-image, get background-image:
var backgroundImage = $('body').css('background-image');

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.

How do you change the background color of an <input> element with javascript

I have a <input> element that I want to change the background color on. The code I am currently using is this (but it is not working):
var allBlanksLoc = document.getElementById('text');
var allBlanks = allBlanksLoc.getElementsByTagName('input');
for(i=0; i<allBlanks.length; i++) {
var currentBlank = allBlanks[i];
var wordNum = blanks[i];
var blankWord = text[wordNum];
var usrAnswer = currentBlank.value;
if (usrAnswer != blankWord) {
currentBlank.style.backgroundColor = "red";
}
}
The third to last line being the most important
Update:
I fixed the camelCase on it but it still does not work. Any ideas of bugs there?
The full code is here: http://jsbin.com/imolo3/edit
Case is important. What you need is
document.getElementById('test').style.backgroundColor='red';
However
it would be better to use a css rule and use javascript only to add the class to the element.
CSS Rule
input.invalid {
background-color: red;
}
Javascript
element.className = 'invalid';
It should be backgroundColor - notice the capital C, JavaScript is case-sensitive.
Are you sure that this script is running at the right time? If it runs before the page is fully formed, the appropriate elements might not be present.
So not to repeat the solutions other users gave.
I personally use JQuery (and it's where any javascripter ends, overall for browser compatibility issues), and it would:
$(currentBlank).css("background-color","red");

How to reset the style properties to their CSS defaults in 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);

How can I undo the setting of element.style properties?

I have an element in my document that has a background color and image set through a regular CSS rule.
When a certain event happens, I want to animate that item, highlighting it (I'm using Scriptaculous, but this question applies to any framework that'll do the same).
new Effect.Highlight(elHighlight, { startcolor: '#ffff99', endcolor: '#ffffff', afterFinish: fnEndOfFadeOut });
The problem i'm facing is that after the animation is done, the element is left with the following style (according to FireBug):
element.style {
background-color:transparent;
background-image:none;
}
Which overrides the CSS rule, since it's set at the element level, so I'm losing the background that the item used to have...
What I'm trying to do is, in the callback function I'm running after the animation is done, set the style properties to a value that'll make them "go away".
var fnEndOfFadeOut = function() {
elHighlight.style.backgroundColor = "xxxxx";
elHighlight.style.backgroundImage = "xxxxx";
}
What I'm trying to figure out is what to put in "xxxx" (or how to do the same thing in a different way).
I tried 'auto', 'inherit', and '' (blank string), and neither worked (I didn't really expect them to work, but I'm clueless here).
I also tried elHighlight.style = ""; which, expectably, threw an exception.
What can I do to overcome this?
I know I can put a span inside the element that I'm highlighting and highlight that span instead, but I'm hoping I'll be able to avoid the extra useless markup.
Chances are you're not setting the style on the correct element. It's probably being set somewhere up the line in a parent node.
elHighlight.style.backgroundColor = "";
elHighlight.style.backgroundImage = "";
You can also remove all the default styling by calling:
elHighlight.style.cssText = "";
In any case, you'll still have to do this on the specific element that is setting these properties, which means you may need to do a recursion on parentNode until you find it.
Try
elHighlight.style.removeProperty('background-color')
elHighlight.style.removeProperty('background-image')
have you tried elHightlight.style.background = "";?
I have a highlighter code on my site and this works
function highlight(id) {
var elements = getElementsByClass("softwareItem");
for (var ix in elements){
elements[ix].style.background = ""; //This clears any previous highlight
}
document.getElementById(id).style.background = "#E7F3FA";
}
An HTML element can have multiple CSS classes. Put your highlight information inside a CSS class. Add this class to your element to highlight it. Remove the class to undo the effect.

Categories

Resources