LESS - set variables on the client side - javascript

I have created a LESS (http://lesscss.org/) version of a simple css grid solution (http://simplegrid.info/. Now I can happily roll my own grid sizes with the server script from LESS (lessc). That's working for me.
For demo purposes I would like to create a HTML page, where I can put the size of the css grid in a textbox and the grid would change dynamically. Beginning of the demo is here:
http://jsfiddle.net/8QHNc/
So instead of changing #layoutwidth: 720px; in the <style rel="stylesheet" type="text/less" > section I would like to pass these variables to the LESS interpreter.
Can these be done with the client side usage of less? Can I define global variables or pass them as parameters to less.js somehow?
I am aware that I could do this without the usage of LESS (preferably with jQuery o. sth.) - but I figured since it is already there...

I do not know if the parser takes any arguments, but why would you refuse to use the built-in javascript evaluation, e.g. adding something like:
#layoutwidth: `document.getElementById("inputLayoutWidth") + "px"`;
to your Less-Stylesheet. Or, using jQuery, as you proposed:
#layoutwidth: `$("#inputLayoutWidth").val() + "px"`;
while using an input field like
<input type="text" id="inputLayoutWidth" value="720" />
and invoke parsing each time the input field is changed.

If you are using 3.x version of less CSS than u can set them in javascript code as well.
less.modifyVars({
'#buttonFace': '#5B83AD',
'#buttonText': '#D9EEF2'
});
I don't know if this method is also present in older version of less.

Related

How do I tag my CSS file with a version number that jQuery can read?

I'm making a Javascript library that comes with a CSS file. I would like for the JS to check the CSS file version.
My best idea is CSS like this
body { someproperty: "v1.3.1"; }
and then you can have JS code like this
console.log($("body").css("someproperty"))
But I'm having a hard time finding the perfect property. Is there some semi obsolete one that takes an arbitrary string or number?
Any other ideas?
#Niet the Dark Absolless gave the perfect answer to my question, but I ended up handling my CSS purely in JS:
$('head').append(my_css)
This gives me one single file to distribute, which can never get out of sync with itself. Good Times!
Actually, there is. Sort of.
body {content:"Hello, world!";}
Because it's not a psuedo-elment, it has no effect.
But if you then do:
console.log($("body").css("content"));
... Close enough! -- Just need to strip the quotes from the start and end ;)
console.log($("body").css("content").slice(1,-1));
Create a javascript file which defines the version and then load the stylesheet via javascript. Include the javascript file instead of the CSS file:
function getVersion()
{
return '1.0';
}
$(document).ready(function()
{
$('head').append('<link rel="stylesheet" href="test.css" type="text/css"/>');
});

Do custom markup tags placed in an HTML document affect the flow and is it possible to parse them with JS? [duplicate]

This question already has answers here:
Is there a way to create your own html tag in HTML5?
(18 answers)
Closed 8 years ago.
Would it be possible to do the following
<body>
<main>
<!-- CONTENT -->
</main>
<foot>
<!-- FOOTER CONTENT -->
</foot>
</body>
if I then wrote some JavaScript that did something along the lines of the following. Please note that I don't want you to write the actual code that goes here. This is just a mockup of the core functionality.
for(elem inside main){
elem.makeItBig();
}
for(elem inside foot){
if(elem is img){
elem.makeItSmall();
}
}
I am aware of this post Is there a way to create your own html tag in HTML5?. But I don't really want to create tags to style them but rather to provide identifying attributes to the DOM which I can hook into using JavaScript. Imagine something kind of like a class, but used in a way that you can stitch lots of PHP generated parts together using these tags.
If you use a made up tag in HTML is it ignored by your browser or will it throw an error.
You can use your own tags as far as I'm aware.
You'd need to do some mucking about to get them to work in older IE browsers.
The more important point is - why on earth would you want to? It wouldn't make your code very maintainable or future-proof. Just use classes on proper elements.
Can you create custom tags? yes. Is it a good idea? not really because your tag may not be recognized by some browsers as a valid html standard. you can check this: http://www.w3.org/MarkUp/html-spec/html-spec_4.html#SEC4.2.1
For custom elements specifications you can look at standards specification for custom elements : http://w3c.github.io/webcomponents/spec/custom/
Although your approach seems nice, just think about changing the size of another group of elements ... you would probably use the same function so why not do this:
var makeItBig = function(elem){...};
for(elem in main){
makeItBig(main[elem]);
}
this way you won't have to create a new method for each element you need to change.
But if you really need it that way you can make it like this:
var makeItBigFunction = function(){var elem = this; ...};
// create new methods
for(elem in main){
main[elem].makeItBig = makeItBigFunction;
}
// make use of them
for(elem in main){
main[elem].makeItBig();
}
Notice that there is a big difference between DOM object's properties (or methods) and HTML attributes.
Read more about it: Properties and Attributes in HTML
Feel free to use HTML5 tags like <content>, <header>, <footer>, <aside> etc.
You can read more about them here: http://www.w3schools.com/html/html5_new_elements.asp in section "New Semantic/Structural Elements". Those should be considered as supported in most modern browsers. Actually, you may use any other custom tags, however their default properties (display, position etc.) may be unpredictable.

jQuery $().css("content") returning the string "normal" in IE9

I'm using the CSS content attribute to pass some values from my LESS stylesheet to JavaScript (to use some colors defined in LESS in Canvas elements).
To make my life easier I decided to place these values in a easy way to parse them in JavaScript.
LESS code:
div#colorChart-critical {
content:'#{critical-highest},#{critical-veryhigh},#{critical-high},#{critical-low},#{critical-medium},#{critical-verylow}';
}
which when compiled brings the following CSS:
div#colorChart-critical6 {
content: '#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00';
}
Then I try to read them using jQuery:
$("div#colorChart-critical").css("content").split(",");
The problem is that in IE9 calling $("div#colorChart-critical").css("content") is returning the string "normal" for some reason. Opera, Firefox, Safari and Chrome works fine.
Why does this happen in IE9?
Any work-around this issue on IE9? If not any other CSS atribute I can put random texts in?
I could use something like:
background: url(#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00);
But this would generate errors on the console.
It's because content as defined in CSS2.1 doesn't work on elements, only on the :before and :after pseudo-elements. IE9 is simply following the CSS2.1 spec here, which mandates that content on elements be computed to normal, always.
I don't know why other browsers would return the value you have defined, especially considering that .css() makes use of getComputedStyle() on those browsers. If they're implementing CSS2.1 content, then they're violating CSS2.1 by not computing the value to normal. If they're preparing for a late CSS3 implementation, whatever that may be, then it would make sense that they implement it on actual elements somehow... shame on them either way.
Which brings me to another point: if you're not actually trying to use CSS to modify the content of an element, don't use content, even if the fact that it's not defined for use with elements is the reason you're making use of this technique in the first place. You can try assigning those colors to certain classes, creating a hidden element and querying that element's color styles instead.
BoltClock answer shows the cause of my problems. I found a work-around by using the font-family instead of the content CSS property.
My LESS code:
div#colorChart-maincolors {
font-family: '#{colorChart1},#{colorChart2},#{colorChart3},#{colorChart4},#{colorChart5},#{colorChart6}';
}
Which compiled into CSS gives:
div#colorChart-maincolors {
font-family: '#c0392b,#2980b9,#2ecc71,#f1c40f,#ecf0f1,#34495e';
}
The string can be acquired using:
removeQuotes= function(string) {
return string.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
};
removeQuotes($("#colorChart-maincolors").css("font-family")); //add a .split(',') to get the colors as an array
The function removeQuotes is necessary because each browser adds a different kind of quotes into the return of getComputedStyle (and by extension the jQuery .css() method). IE9 adds a double quote, Webkit adds a single quote.
See this post on CSS tricks: http://css-tricks.com/making-sass-talk-to-javascript-with-json/ for more information.
you can use replace(/["']/g, "") to remove extra quotation from string
""string"" will be change to "string"

JavaScript variable name and HTML input name attribute: namespace collision?

In an HTML file I have the following:
<input type="..." name="myInput1" />
In a corresponding JS file I have the following variable which will hold the string value of that input after blur:
var myInput1;
Is there any problem in having these two identical names? I'm guessing that the namespaces are separate so it is ok.
Short answer, no problem whatsoever.
A short answer is, indeed, no. However, it also greatly depends on how you use the variable. Let's consider that you use javascript for validating that the variable is set as follows:
if(myInput1) {do something}
If you also decide to set the id to be the same as the name is as follows (cause you didn't specify that, it can be anything):
<input type="myInput1" name="myInput1" />
your variable myInput1 will be set to contain the DOM element and won't be empty anymore.
This link between JS and HTML is not only interesting but can be used to create an exploit as described in the section 3.1.2 of Postcards from the post-XSS world (that's where I have the idea from - and yes, it still works even though the article is from 2011).

Create new (not change) stylesheets using jQuery

We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas

Categories