Use CSS content content in element to exclude store information for javascript

I use the variable.less configuration file to store all relevant project information. One of the information is the breakpoint between the layout and the layout of the PC. I also need this information in javascript, and I did not know how to get it (without storing it in the data attribute, because I wanted to save all the design variables in one file).

So, I finally found that: I save the breakpoint in .less variables:

@bk-point: "500px"; 

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

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

Similarly, this does not affect the design (the "content" property is not displayed on the element, only on the pseudo-element), and I can get it very easily with jQuery:

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

And all my variables are in fewer files.

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

Thanks for your advice!

Sebastien.

PS:
1. works in firefox 21.0 and in chrome 27.0
2. and of course, if you have a better solution ...

+4
source share
1 answer

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

No matter how cool the idea may seem, I would not feel comfortable using it in production. I think you should agree that your js variables and css variables will be in two different files, and then just apply the values ​​through the data attributes.

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

All you really do is save the string in html, so you can use a rather obscure element like counter-reset and then capture 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' 

A simple regular expression function to save you from the "breakpoint" part of the returned string, and you have what you are looking for. btw, can do this for any other css property that is not used, for example:

  border-width: @bkpoint; border: none; 

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

+1
source

Source: https://habr.com/ru/post/1500006/


All Articles