2

I have as the following style in a css file

#galleryImages{
    position:absolute;
    top:24px;
    left:41px;
    width:900px;
    moving:false;
}

When I try to access it through Javascript, it returns undefined

The external css is correct, it returns other style variables properly as well as the getElementById

alert("External: " + document.styleSheets[0].cssRules[2].style.moving + 
    "\nInternal: " + document.getElementById("galleryImages").style.moving);

It gives an alert with:

External: Undefined
Internal: Undefined

Is there a way to access a custom CSS variable through javascript?

Thank you in advance

D M
  • 23
  • 3
  • 4
    As far as I know, non-standard CSS definitions are completely ignored by the browser, as such it won't appear in any attempt to reference it. I might be wrong, but I'm fairly certain I'm not. – Khez Apr 03 '11 at 21:25
  • Is there any reason you are using a custom css variable? If your site is HTML5, then I'd go with a data attribute, which were designed to solve this situation. http://html5doctor.com/html5-custom-data-attributes/, even if it's not html5 I'd still argue a data attribute is a better solution. – Matt Greer Apr 03 '11 at 21:26
  • see this [question](http://stackoverflow.com/questions/2926326/can-i-access-the-value-of-invalid-custom-css-properties-from-javascript) and this mozilla [bug](https://bugzilla.mozilla.org/show_bug.cgi?id=116694). – Anurag Apr 03 '11 at 21:30
  • What does that `moving` CSS property do? – Šime Vidas Apr 03 '11 at 21:30

1 Answers1

4

Most (all?) browsers won't load unknown CSS into the DOM, and JavaScript cannot directly access CSS styles directly, only the ones that are loaded into the DOM.

The only way I can think of would be to implement your own CSS parsing JavaScript, but for the mostpart, that would probably be excessive for what you want to do, and a pure JavaScript solution or a class value would better.

e.g. In HTML

<div class="moveable"></div>

Using that example, you could use your JavaScript to get the classname of the element, and if it has the "moveable" class, you know it can move.

EDIT: In @Anurag's posted link to the Mozilla bug, it is mentioned that unknown CSS properties are to be ignored as part of the CSS 2.1 specification.

Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65