Is there anyway to use javascript get the attributes determined by CSS? - javascript

For example,
<html>
<head><link rel="stylesheet" type="text/css" href="theme.css"></head>
<body>
<img id="tmp"></img>
</body>
</html>
in theme.css
img#tmp{
width:120px;
top:0;
left:0;
}
Is there anyway that I can get the width of the image "tmp" directly by JavaScript? Something like
var temp=document.getElementById("tmp"); var width=temp.style.width?

Here you go:
getComputedStyle( elem ).getPropertyValue( 'width' )
where elem is the DOM element.
Live demo: http://jsfiddle.net/7h4cg/
Btw, some older versions of some browsers do not support this code. If you need a cross-browser solution, use a cross-browser library.

You'll definitely want JQuery's help on this. Here is the list of all JQuery functions that can help you access all the style information you would want (hopefully).
Btw, if you're not familiar with some sort of Javascript library, it's probably a good idea to learn one.

I 2nd Nadir's motion, however in your direct example you can change your code to:
var temp=document.getElementById("tmp");
var width=temp.style.width;
In your own example, you have used the getElementById incorrectly by pluralizing it.
This comment sums up why.

What you're after is the computed style of the element. As usual, IE6-8 does it differently, so we need to do some sniffing:
var getStyle = window.getComputedStyle ? function (elem, prop) {
var styles = getComputedStyle(elem, null);
return prop ? styles[prop] : styles;
} : function (elem, prop) {
return prop ? elem.currentStyle : elem.currentStyle[prop];
};

This is my cross-browser inline function:
function getComputedStyle(elem, styleAttr){
return (elem.currentStyle ? elem.currentStyle : document.defaultView.getComputedStyle(elem, null))[styleAttr];
}

Some browsers will return the literal style width and height, as it was written in the css- pehaps as a pecentage or an em multiple, while others translate all style dimensions to pixels.
In this case, I'd use document.getElementById('tmp').offsetWidth to be sure to get the rendered width in pixels, no matter how it was assigned.

Related

Why CSS isn't working on innerHTML in Pure JavaScript? [duplicate]

<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
google
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>
The first and the second alert display nothing other than a empty string, which I thought should be none and block.
However after the intensionally display setting, the third alert finally alert none.
But Why? How could I retrieve the display property correctly?
Thanks.
The .style.* properties map directly onto the style attribute, not to the applied style. For that you want getComputedStyle.
I'd give serious consideration to toggling .className and separating the presentation from the logic entirely.
You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle() whereas the nearest equivalent in IE is the element's currentStyle property:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}
I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.
If you can use jQuery, there is a method called .is
To check if something isn't displayed, I'd do ... $('someSelector').is(':visible') ...
This would return false if display attribute is set to None.

How to get an html element's color? [duplicate]

<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
google
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>
The first and the second alert display nothing other than a empty string, which I thought should be none and block.
However after the intensionally display setting, the third alert finally alert none.
But Why? How could I retrieve the display property correctly?
Thanks.
The .style.* properties map directly onto the style attribute, not to the applied style. For that you want getComputedStyle.
I'd give serious consideration to toggling .className and separating the presentation from the logic entirely.
You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle() whereas the nearest equivalent in IE is the element's currentStyle property:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}
I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.
If you can use jQuery, there is a method called .is
To check if something isn't displayed, I'd do ... $('someSelector').is(':visible') ...
This would return false if display attribute is set to None.

Cross-browser dynamic setting of a CSS property

I have a function that gets many pieces of data and sets a CSS property for a defined element.
Here is the code:
function setStyle(element,property,target){
element.style[property] = target;
}
var EL = document.getElementById("id");
setStyle(EL,"width","50px");
It works well in most browsers but not for IE6–IE9.
I've found document.defaultView.getComputedStyle and element.currentStyle[type], but these methods get style and I can't use them to set.
Is there any way to do that for old IEs?
i don't want to use jQuery or any other JS library, thanks.
The default way would be element.style.property = "value", like:
document.getElementById("id").style.width = "50px";
There's no reason why it shouldn't work. But, as an alternative, consider setting the css style in a class, and adding it to the element by the className property.. It is widely supported:
css:
.myClass { width: 50px; }
js:
document.getElementById("id").className = "myClass";
EDIT
Yet another way around, that works in IE8+ (If you don't really need anything lower) would be setting the actual style atribute to the DOM element, so you can get the property as a parameter:
http://jsfiddle.net/ppf5qcvo/
function setStyle(element,property,target){
element.setAttribute("style", property + ":" + target);
}
var el = document.getElementById("test");
setStyle(el, "color", "red");
Have you considered using jQuery? It handles all the cross browser issues for you. You could accomplish the same thing with the following statement:
$('#id').width('50px');

How do I compare css style values using JavaScript if conditions?

I got a quick question. If I want to compare a style left / right value with another coordinates (lets say mouse) how do I do it?
Here is what I tried without mouse coordinates but for some reason my condition never executes...
<style>
#container
{
position:absolute;
left:400px;
top:200px;
}
</style>
<script>
function moveExit(){
var containerId = document.getElementById("container").style;
if(containerId.left == 400 + "px")
containerId.left = 395 + "px";
}
</script>
And here is my body:
<body>
<div id="container">
<img
src="Images/image.jpg"
onmouseover="moveExit();"
/>
</div>
</body>
This is my first time playing around with javascript.. Thanks!
you need to use computed style for this purpose.
How do I get a computed style?
var left = window.getComputedStyle(document.getElementById("container")).left
for IE8 you have to use currentStyle proeprty as computed style is not supported.
document.getElementById("container").currentStyle.left
Cross-browser (IE8-) getComputedStyle with Javascript?
Try something like this:
http://jsfiddle.net/xtJA4/
$(document).ready( function() {
$("#container").mouseleave(function() {
if ($(this).css("left")=="400px") {
alert("Left = 400px");
}
});
});
There are of course changes that can be made to this, but for what you're needing this should work fine. You can of course go and change the alert() function to match what you need (modifying the left offset), but hopefully this helps!
While I'm not 100% sure what exactly you are looking to accomplish, here are a few comments, and suggestions for your code.
Rather than user javascript, I would use jQuery. This is something that David has suggested previously. One of the great advantages of jQuery is that it gets around most browser incompatibility issues.
To do this with jQuery you'll need to import jquery, and then you can use it like so:
<script type="text/javascript" src="./jquery/jquery.js"></script>
<script type="text/javascript">
function moveExit(){
var $element = jQuery('#container');
$element.css('left', '350px');
}
</script>
Please also notice that I have added the "type" attribute to the script elements.
As a side-note I would also remind you to add "alt" attributes to img elements. Good for accessibility and for when the images are blocked for whatever reason.
With greater understanding about what you are trying to accomplish a better answer can be provided.

How to detect text direction of element using Javascript?

What's the best way to detect the text direction of an html element using Javascript? I would expect to get either "rtl" or "ltr".
<div dir="ltr" id="foo">bar</div>
<div style="direction:ltr" id="baz">quux</div>
<div dir="ltr"><div id="jeez">whiz</div></div>
How would I test for the direction on "foo", "baz" or "jeez"?
getComputedStyle is available in modern browsers (IE9+ and the others).
getComputedStyle(document.getElementById('foo')).direction
http://jsfiddle.net/m8Zwk/
Reference to getComputedStyle on Mozilla Developer Network
Try this
document.defaultView.getComputedStyle(document.getElementById('baz'),null)['direction'];
OR
style = document.defaultView.getComputedStyle(document.firstChild,null);
console.log(style.direction);
#explosion-pills answer is correct. I did some more research for IE compatibility and came up with the following:
function getDirection(el) {
var dir;
if (el.currentStyle)
dir = el.currentStyle['direction'];
else if (window.getComputedStyle)
dir = getComputedStyle(el, null).getPropertyValue('direction');
return dir;
}
This should even work on Firefox 3.6 which requires null as the second parameter to getPropertyValue.
Since this gives more information I thought I would post it in case it helps someone.
You can simply use the style object:
console.log(document.getElementById('baz').style.direction);
DEMO
Take note that this object of the DOM only represents the in-line styles of an element, it doesn't apply to any css style sheets.

Categories