Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use css property content on element to exceptionnaly store information for javascript

I use a variable.less config file to store all relevant information about a design. One of the information is the breakpoint between mobile layout and PC layout. I also need this information in javascript, and I didn't know how to get it (without storing it in a data-attribute, because I wished to keep all design variables in the same file).

So I finally found that : I store my break point in the variables.less :

@bk-point: "500px";

I use the css property "content", but not on a pseudo-element, but on any tag (less file):

#any-div {
   content: "@{bk-point}";
}

Like this, this doesn't affect the design ("content" property doesn't show on element, only on pseudo-element), and I can get it very easily with jQuery :

var bkPoint = $('#any-div').css('content');

And all my variables are in the less files.

This is perfect for what I want, but is there any side-effect that I don't see ? Is this a bad practice for reasons I cannot imagine ?

Thanks for your advices !

Sébastien.

PS:
1. works in firefox 21.0 and in chromium 27.0
2. and of course, if you've got a better solution …

like image 486
Sébastien Avatar asked Nov 11 '22 22:11

Sébastien


1 Answers

The css 'content' property is only valid on pseudo elements: https://developer.mozilla.org/en-US/docs/Web/CSS/content

As much as this seems like a cool idea, I wouldn't feel comfortable using it in production. I think that you should accept that your js variables and css variables will be in 2 different files and then just apply the values via data-attributes.

However, if you really want a creative way to do this only from the css files that can print to the html and thus interact with the javascript, what about using valid properties that will not affect the design?

All you are really doing is storing a string in the html, so you could use a rather obscure element such as counter-reset, and then grab the value via jquery.css()

variables.less: @bkpoint = 500;
css:
#any-div {
   counter-reset: break-point @bkpoint;
}
jquery:
$('#any-div').css('counter-reset'); // returns: 'break-point 500'

simple regex function to get you rid of the 'break-point' part of the returned string and you've got what you're looking for. btw, can do this on any other css property not in use, such as:

 border-width: @bkpoint;
 border: none;

specs on counter-reset in case you're interested: http://www.w3.org/TR/CSS2/generate.html#propdef-counter-reset

like image 159
DMTintner Avatar answered Nov 14 '22 23:11

DMTintner