Confusions with CSS and JavaScript relations? - javascript

I have table cell which has class "cellActive". Which has following defination
.cellActive{background:"#DDDDDD"}
Now i am trying to read the background color property for the cell and it comes null/"".
var bgColor = cell.style.backgroundColor; // returning ""
Is that something mistake on my part of its by behavior. If CSS class is assigning CSS to element can't we read its value in JS ? Does this mean that if we are not assigning property directly to the element we cant get it if in case its inheriting it ?

The style attribute contains only explicitly set properties, not those inherited from a class. You need the so-called "computed style" that reflects the properties the way they were actually rendered.
See the accepted answer to this question for a very good cross-browser solution.

There is a difference between "background" and "background-color". Also, the "style" property means the style property of the element has been set in either HTMl or Javascript. Use "computedStyle" for other cases. That means using the getComputedStyle() method, which you can learn about here.

there are various ways to access CSS in JavaScript Element.style actually accesses what is written to the style attribute. to get the full CSS rather use getComputedStyle().

Related

Jquery- How to change backgroundColor using prop method?

Can I change the backgroundColor property value using the prop method?
I'm new to programming. :)
This is what I have,
$('ul').prop('backgroundColor','red');
I read the chapters on this book I'm reading and it is my understanding that I can change properties from the DOM using the prop method in jquery. I can change other DOM properties such as className. Why not backgroundColor? Writing this I also tried atr.
$('ul').attr('background-color','red');
In this case, attr does have access to CSS properties, correct? However when using the prop method, we do have access to some CSS properties? Why is backgroundColor created?
I know the best way to go about changing the background color would be to use the css method, in jquery that is. I just wanted to know if or not the prop or atr method can change the background color, and why not, if not. I believe this will give me a better understanding of the DOM.
Thanks!
You need to use .css() to manipulate the CSS properties.
$('ul').css('background-color','red');
The backgroundColor is nested property of style property of the element so .prop('backgroundColor','red'); won't works here.
Instead, you can set property by getting DOM element. In case there is multiple element then you need to iterate over them.
$('div')[0].style.backgroundColor = 'red';
// if there is multiple elements
$('div').each(function() {
this.style.backgroundColor = 'red';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>a</div>
Or use css() method to set any style property.
$('div').css('backgroundColor', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>a</div>
$('ul').attr('background-color','red');
does not work as the attribute is "style" and backgroundColor is a property of that.
You need to use:
$('ul')[0].style.backgroundColor = 'red';
When coding straight html you can specify inline css like this:
<div style="background-color:#00000"></div>
Therefore using jquery, you can leverage this feature by using the attr method.
$('div').attr('style','background-color:#00000;');
So in a way, yes you can alter css using the attr method. Because there is an "attribute" for style (css) in html and changing html attributes is basically what attr is for.

Does CSS code initialize .style properties of DOM objects?

Background:
I created a simple DOM event example: see jsfiddle here.
<div id="squirrel" onmouseover="toggleFloat(this)">
<p>Click me!</p>
</div>
<script>
function toggleFloat(ele){
var current = ele.style.cssFloat;
console.log("cssFloat: "+current);
if(current==="left")
ele.style.cssFloat="right";
else
ele.style.cssFloat="left";
}
</script>
Accompanying css:
#squirrel{
float:left;
}
Odd behaviour was noticed: In the DOM, the #squirrel's initial value for the cssFloat property was "". (Open the developer console to see this. Or notice that the #squirrel doesn't move until the second event fires.).
My question is: Should the CSS code not have initialized the cssFloat property of the DOM object? ...or any of the style properties for that matter?
The style property of an element represents its inline style (defined with the style attribute).
Those are not modified by the css rules defined in a your css file. The browser computes the final style based on those rules and the inline style.
The final computed style can be retrieved using MDN: Window.getComputedStyle()
You generally should avoid to use inline style attributes. Normally you should try to use class to manipulate the appearance of a certain element. Also the use of the style property to dynamically change the inline style should only be used if there is really no way around it, e.g. if you need to move an element dynamically. You could also read the answer to Inline tags vs. inline css properties for more informations.
CSS never modifies the DOM.
The 'style' attributes in the DOM are merged-with/override the CSS defined in stylesheets.

Change css class atributes dynamically from Jquery?

I have a situation in my project , in css I have a class
which is empty for now
#version_mobile.hidden
{
}
and in js Im doing this
this.$("#version_mobile.hidden").css({right: - window.text_mobile_width});
(I supose my selector is bad ?)
how to add "right" atribute to this class with this dynamically created value ?
to class become
#version_mobile.hidden
{
right : -450px;
}
Btw I need to use this class because the animation is working with it :/
.css() function changes the inline css style but has no effect over the css classes at all.
As pointed out in the documentation:
When using .css() as a setter, jQuery modifies the element's style
property.
You can also change the classes by using the addClass(), removeClass() or even the toggleClass() functions of jQuery.
You cannot add to the class properties, but you can apply rules to the element style.
this.$("#version_mobile.hidden").css({"right", "- window.text_mobile_width"});
you can not add definations for class in jquery.
but you can add any style to your selecter.
What are you trying to achieve?
you cannot add a property to the css file using this.
what you should look at is you apply this id or class to your html elements
and access the elements in the javascript using the jquery selectors
$(#selector) and modify the property using .css.
So you will achieve the same result this way as any existing property style for that
element will be overridden with your latest style put through the jquery.
It's technically possible to modify style rules on the fly, but it's difficult.
In the document object you will find an (array) property called styleSheets, with one entry for each referenced stylesheet.
Each stylesheet object (of type CSSStyleSheet) has an insertRule method, which you can use to create new rules, or delete existing rules. What appears to be difficult is enumerating the existing set of rules so you can find which one to modify or delete.
That said, it's generally far preferred to simply change an element's classes than to try to dynamically change the styling of an existing class.
See also http://davidwalsh.name/add-rules-stylesheets

Should JavaScript be able to read element positions set in CSS through the element's style property?

On http://jsfiddle.net/Xs9e2/ there are two elements, named ONE and TWO. The element ONE is positioned by assigning to the style property of the DOM element using JavaScript. The element TWO is positioned using CSS.
The HTML renders as expected.
There is a button one can press to have the left and top properties of each of the two elements alerted. We only see the properties that were set in JavaScript, not the ones set in CSS.
What is the reason for this exactly? Shouldn't we be able to read the CSS properties via JavaScript? I may have specified something incorrectly. I know about the "offset" properties and I know about JQuery; I'm just puzzled why this old-fashioned DOM manipulation isn't working as I would expect. What am I missing?
The style attribute is, well, an attribute. That is you can only access the values given in the HTML element's attribute style:
3.2.3.8 The style attribute
The style IDL attribute must return a CSSStyleDeclaration whose value represents the declarations specified in the attribute. (If the attribute is absent, the object represents an empty declaration.) Mutating the CSSStyleDeclaration object must create a style attribute on the element (if there isn't one already) and then change its value to be a value representing the serialized form of the CSSStyleDeclaration object. The same object must be returned each time.
Styles given with CSS don't set the element's attribute, thus you cannot access it with .style.
However, you can use getComputedStyle.
You can use IE-specific currentStyle which has all styles or better standard one (as pointed out) getComputedStyle supported in IE9+, not style which reflects inline styles only.
alert("one at "
+ JSON.stringify([getComputedStyle(one).left,getComputedStyle(one).top])
+ "two at "
+ JSON.stringify([getComputedStyle(two).left,getComputedStyle(two).top]));

Can you target classes with jquery?

What I want to do is $('.class.img').css('cellpadding', variable);
It doesn't seem to be working. I tried googling to no avail. Any help would be appreciated. I'm trying to apply it to an image inside the element with the given class.
CSS applies the styling properties inline as in style="..." and does not modify the .class itself.
$('.class').css does not do anything.
$('.class').css('color','red') writes a color style
$('.class').css('color') reads the color style
So to target your img elements within an element with class "cellBox":
var borderx = "1px solid red";
$('.cellbox img').css('border',borderx);
(That sets border, but you can set padding the same way.)
Check working example at http://jsfiddle.net/SBjfp/2/
(Note that the jQuery documentation says that shorthand properties like padding or border are not supported; this mostly applies to getting the properties; setting [as above] usually works because it's supported by the underlying browser's implementation.)
The jQuery selector engine works perfectly well with class selectors.
The only thing clearly wrong with this (there might be other things, but you haven't provided any context (such as what the document looks like or when the statement is run)) is that css is a function, and you aren't calling it (i.e. css('foo')).

Categories

Resources