Wednesday, July 25, 2012

JavaScript Element's Style Properties Doesn't Received Bug (Solved!)

There is a problem when the JavaScript does not return the style's properties.
The problem that even when retrieving element by id or class name won't give you it's style properties.
I investigated this situation in deep roots.
// some times this code can be improper.
var x = getElementById('someID');
alert(x.style.backgroundColor);

Previous example may work under many circumstances, but sometimes fails to fulfill required operations.
If we dump the object into the console with
var x = getElementById('someID');
console.log(x.style);
// or even
console.log(x);
When problem appears, you probably won't find anything in the style. The object will show the properties, but the values are blank or null,underfined... anything but not the values we require :)
This is funny bug :)
Another circumstance under which this code will work is if you have typed the style in-line. But we are ninjas, we shouldn't use inline styles.

Javascript element doesn't return styles -> Problem resolution!
It is not a secret that JavaScript contains different ways of retrieving styles, but...
Some of theme working and some of them is not... some works in IE, some doesn't...
I am using next method:
//Usage example:
var _el = document.getElementById('someID');
var _elBGColor = getTheStyle(_el, 'backgroundColor');

function getTheStyle(_elm,_prop){
   var x ='';
   if(window.getComputedStyle){
      x=getComputedStyle(_elm);
   }else{
      x=_elm.currentStyle;
   }
   return x[_prop];
}

This function will satisfy your need.:)
But...
May be slightly improved in case you need all the styles of the element.
Let's we take a look at universal function:
function getTheStyle(_elm){
   if(window.getComputedStyle){
      return getComputedStyle(_elm);
   }else{
      return _elm.currentStyle;
   }
}

This fix is perfectly working retrieving any of previously "blank" style properties.

Sincerely,
Ruskevych Valentin


Other JavaScript Tutorials and How To

How To Verify Function exists in a JavaScript Class
JavaScript OOP Basics
TableSorter Installation a Detailed Tutorial.

No comments: