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.
Related
I'm not sure why, but I can't seem to get this to work.
Here is my function to enlarge my font.
<script type="text/javascript">
function growText() {
var text = document.getElementById("t_left_text");
text.font-size=22px;
</script>
And here is where I call it
<div id="t_left" onclick="growText()">
<br />
<p id="t_left_text">Mountains are beautiful land structures <br /> that are a result of plate tectonics.</p>
<br />
</div>
Try:
text.style.fontSize = "22px";
DEMO: http://jsfiddle.net/C2MWN/
When you want to change an element's CSS, you need to use the style property. To determine the name of the specific style property, the CSS name is converted to camel case - "font-size" becomes "fontSize", so that the identifier is valid in JavaScript.
While setting the style properties definitely works, and although this is a very simple example, it might be easier to deal with adding and removing a class. This is especially useful when setting multiple CSS properties. The class could be defined as:
.enlarged-font {
font-size: 22px;
}
And you would manipulate the text.className property (and/or the classList property).
Depending on the browser you're using, you could have easily provided a better description (as obvious as it was for some of us) of the problem by using the JavaScript console in the browser. In Firefox, you could use Firebug. In Internet Explorer and Chrome, you could use Developer Tools. If installed/enabled, these can usually be brought up by pressing the F12 on your keyboard.
Also, don't forget to close your function with a }.
Reference:
style property: https://developer.mozilla.org/en-US/docs/DOM/element.style
classList property: https://developer.mozilla.org/en-US/docs/DOM/element.classList
Use below code
function growText() {
var text = document.getElementById("t_left_text");
text.style.fontSize ="22px";
}
Working example http://jsfiddle.net/D2anZ/
Here's a version that uses CSS to accomplish what you want. That way if you want to do this to different sets of text at the same time, and want to change that font size, there's only one place you need to make the change. (Or if you also want to add other css properties (color, etc.)
Fiddle
JavaScript
function growText() {
var text = document.getElementById("t_left_text");
text.className = 'large-font';
}
CSS
.large-font {
font-size: 22px;
}
I tested the visibility of the following div:
<div id="div1">div</div>
with the style defined separately
#div1 {
visibility:visible; //or hidden
}
If the style is defined inline as <div id="div1" style="visibility:visible">div</div> there it's easy to check the visibility in the element.style.visibility property. But the problem is when the style is defined separately (as shown above - #div1, .div1 or div).
And so where can one check the visibility property using only pure javascript? jQuery returns correct style everytime (I dunno how to track it), so how did they do it? Here is one fiddle with my unsuccesful attempts, no tests except jQuery's work:
alert($(el).css('visibility')); // jQuery works well - returns correct property
alert(el.style.visibility); // not works - always empty string
alert(el.offsetWidth > 0 || el.offsetHeight > 0 ? 'yes':'no'); // also not working - always true - http://stackoverflow.com/questions/1343237/how-to-check-elements-visibility-via-javascript
alert(el.getComputedStyle); // undefined - http://stackoverflow.com/questions/4795473/check-visibility-of-an-object-with-javascript
alert(el.getAttribute('visibility')); // not works - of course null
Any ideas on how to succeed? Tested in latest Firefox 15.
getComputedStyle is a global method. Use it as follows:
window.getComputedStyle(el, null).getPropertyValue('visibility');
You are using getComputedStyle wrong:
getComputedStyle( el ).visibility
//"visible"
Demo: http://jsfiddle.net/hMFry/1/
In internet explorer you would use:
el.currentStyle.visibility;
getComputedStyle(el).getPropertyValue('visibility');
I have this code that changes the url every time a user clicks a button in the page.
That works great in safari,chrome,firefox but not in IE 7,8,9.
What could be the problem ?
function setNewNavigationUrls(){
var musicParameter;
if (isMusicOn) {
musicParameter='1';
}else{
musicParameter='0';
}
$("a[href='/']").attr('href', '/?music='+musicParameter);
$("a[href='/collection-glamour-feeling']").attr('href', '/collection-glamour-feeling?music='+musicParameter);
$("a[href='/collection-poetic-moments']").attr('href','/collection-poetic-moments?music='+musicParameter);
$("a[href='/about.html']").attr('href','/about.html?music='+musicParameter);
$("a[href='/contact.html']").attr('href', '/contact.html?music='+musicParameter);
}
Thanks
Shani
You probably should be using ".prop()" instead of ".attr()" to set the "href" of your <a> elements.
$("a[href='/']").prop('href', '/?music='+musicParameter);
// ... etc. ...
With jQuery 1.6, the semantics of "attr()" changed considerably. The "href" attribute becomes a property of the DOM node for the element, and therefore it should be set as a property. The "attr()" method now concerns itself with attributes (via "setAttribute()" and "getAttribute()"). Boolean properties like "checked" and "disabled" are treated in a backwards-compatible fashion following jQuery 1.6.1.
You might want to try and replace: if (isMusicOn) to if (typeof isMusicOn !== "undefined") to be sure the statement gets evaluated correctly.
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.
I want to get an element in the DOM and then lookup what rules in my CSS file(s) are contributing to it's appearance. Similar to what firebug or webkits inspector does. Is there a way to do this in JavaScript?
Update:
I should provide a constraint and a specific example - I am only interested in achieving this in webkit based browsers so cross-browser difficulties are not so much an issue. What I am specifically trying to achieve is this. Let's say I have a stylesheet as follows:
div {
background: #f0f0f0;
}
.example {
padding: 10px;
}
And then let's say some html code like this:
<div id="test" class="example">
<hgroup>
<h1>Test</h1>
<h2>A sample file to play with.</h2>
</hgroup>
<ul class="sample">
<li id="item_1">Item 1</li>
<li id="item_2">Item 2</li>
</ul>
</div>
So then in javascript I want to be able to have a function that can find the selectors from the CSS that are styling the object:
get_selectors_for(document.getElementById('test'))
// should return:
// ['div','.example']
How complicated is it to reverse query selectors knowing we only need to worry about webkit as opposed to all browsers?
This is what you want. WebKit only. I found out about getMatchedCSSRules by looking at the chromium web inspector source.
function getAppliedSelectors(node) {
var selectors = [];
var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');
var i = rules.length;
while (i--) {
selectors.push(rules[i].selectorText);
}
return selectors;
}
A cross-browser solution I've had good success with is http://www.brothercake.com/site/resources/scripts/cssutilities/
It is very powerful and accurate, derives a lot more information than the webkit-only function mentioned above, and it works on all styles (including those that are cross-site and that aren't active or have been overridden).
Is it possible? Absolutely...is it simple (especially cross-browser with IE in the mix), not so much. If you're really interested in doing this, check out the Firebug Lite CSS source here. At least the methods are decently commented showing what information each is fetching.
....or if you're wanting simply to inspect in a browser that doesn't have an inspector, just use Firebug Lite.
There is a reliable way of getting it, mentioned in this blog post:
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView
.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
If you are using Firefox and Firebug, you can try running this code in StackOverflow, to see what you get:
document.defaultView.getComputedStyle(document.getElementById("custom-header"),"")
And with IE and Firebug Lite, you could do:
document.getElementById("custom-header").currentStyle
Well, it's an old subject.
Good for Webkit for offering a solution.
As suggested, I've looked into firebug-lite and... surprise!!
For every node it loops over every rule in every stylesheet checking if the selector matches our nodes or not.