Compiling LESS color definitions to JavaScript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a LESS file with color definitions:
#RED: #CE1512;
#BLUE: #3E83A0;
// ...
I now have need of using these color definitions in my JavaScript as well.
How best to share code like this between LESS and JavaScript?

I ended up coming up with my own solution, though I think I will try to avoid using it all-together (per the reasons listed by alttag).
Vohuman's answer provides another solution, but I don't really like the idea of embedding js directly in my LESS file, so would prefer an approach like below.
I created the following node.js module which will read a json file and output a less file.
var fs = require('fs');
var EOL = require('os').EOL;
module.exports = function (jsonFile, outputFileName) {
var json = require(jsonFile);
var lessFileContent = "";
for (color in json) {
var lessColorDefinition = '#' + color + ': ' + json[color] + ';';
lessFileContent += lessColorDefinition + EOL;
};
fs.writeFile(outputFileName, lessFileContent);
};
Example json file:
{
"RED": "#CE1512",
"BLUE": "#3E83A0"
}
Example usage in Gulp task:
var j2l = require('./baseStyles/jsonToLess');
gulp.task('build-base-less', function() {
j2l('./colors.json', 'colors.less');
});

The short answer to one of your questions is no, no it is not a good idea to use it in your javascript. In general, it is best to keep color and other visual information in CSS, and behavior information in javascript.
Exceptions should be exceedingly rare.

Is this even a good idea?
It depends on the application needs and how it's structured. If you have so many variables and your JavaScript heavily needs them then it makes sense. Otherwise having duplicates in both environments can be considered too.
Which should be the pre-compiled source? (js or less)
JavaScript as LESS compiler also understands JavaScript; however, JSON, in this case is the best option.
Does something like this already exist?
You could create a json file and import it in your LESS file. In JavaScript the file can be easily loaded by using Ajax.

Related

JSON structure in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

How would I setup a HTML page to have a new title each new day? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So my ultimate goal here is to have the site have a new title each day (24 hours).
I am not a very experienced program, but, I am aware something similar could be done with JS.
I saw this idea:
setInterval(function() {
//change title
//document.title = "Some new title";
}, 3000);
I'm not sure how I can take this idea above, which I do not fully understand and make it use, for example, a large array or predefined titles and select one at random each day.
Would it be possible to select the title out of another file or should I have them all in the JS file? On the question just asked, should I have the JS code in the HTML file itself or referenced as a file like a CSS file?
I really appreciate any walkthrough/help I can get on this. I hope your days are well all.
found the solved problem with running code once per day:
Run code once a day
When you will have a function that runs once per day, you just have to reference the title from DOM inside the function and define new title.
var titles = ["title1", "title2", "title3"];
var iterator = 0; // this variable should be incremented every day
// somewhere inside the function that runs once per day
document.title = titles[iterator];
There are 2 ways to import a script on html page.
Inline: https://www.w3schools.com/tags/tag_script.asp
External: https://www.w3schools.com/tags/tag_link.asp
U can even read external file (.txt e.g.) in js, you can look that up, but it's bit more complicated than this.

generating HTML with javascript that contains php and ifs [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a large amount of HTML and CSS which contains some PHP (session based content) this PHP is a must. I need that session information (no cookies wont do).
The html and CSS are standard divs I am looking at this previous question:
Is there a best practice for generating html with javascript
which gives me the answer I need, if I was using just HTML and CSS, but what about if I need to use JS if statements to chose what part of the template needs to be different and what if I need to use PHP to do the same?
I am moving my code away from heavy server side scripting and moving as much as I can to front end processing, but the issue is I need to have some PHP and if statements (js if statements) within the $.template
can I use PHP variables in a JS templating system and how do I use JS IF statements within the templating function?
var moo = 1
var T = $.template('<div>This is code, but what is moo?. if(moo == 1){moo was 1..}else{moo was not 1}</div>')
As I commented, you can declare and check your variables before using it.
Example:
var moo = 2 + 2 == 4 ? "yes moo" : "no moo";
var T = $.template('<div>This is code, but what is moo?. Moo is '+ moo +'</div>');
But if you are working with large data, you should consider to use a string variable and concatenate the new strings as needed:
var str = "<div>";
if( moo == 4 ) str += "moo equals 4";
else str += "moo NOT equals 4";
str += "</div>";
// And when you have your string completed...
var T = $.template(str);
By this way you can concatenate all you need without headaches.

Give a second name to a variable in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have a code source that contains a long variable name (postCustomThumbnailsScrollerHeight).
I don't want to rename this variable for the whole code source so that I easily continue the project, but to have a shorthand of its name. I tried following solution (which works) at the first declaration of the variable, but I am not sure if it is the correct way to do so. I have a different color of d in IDE:
var postCustomThumbnailsScrollerHeight= d= $('.post-scroller').outerHeight();
I am seeking by this question your usual expert advice.
No, this isn't really correct: you're not declaring the d variable, only assigning to it, and thus
making it global (which may or not be desired)
making your code incompatible with strict mode
Here's a solution:
var d = $('.post-scroller').outerHeight(),
postCustomThumbnailsScrollerHeight = d;
Note that this should only be done for readability/typing issues, not for downloaded script size: minifiers should be used for that latter goal.
Be also careful that you're not making an alias, but really two variables. If you assign to one, you won't change the other one. It's hard to give a definite advice without more information but the usual solution is to have namespaced object:
Assuming you have a struct
myApp.thumbnailScrollers.postCustom = {height:...
then you would just assign that latter object to a local variable in a module or function:
var s = myApp.thumbnailScrollers.postCustom
In this case, changing s.height would also change myApp.thumbnailScrollers.postCustom.height.
Probably you have different color because in this case b it's global variable.
As for my opinion will be better to write all definitions on different lines:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;
Although JavaScript doesn't natively support references, you can stimulate them using code such as this:
function d(){
return postCustomThumbnailsScrollerHeight;
}
Then just use d() everywhere. It's not very elegant, but as far as I know it's the only way to get a reference in JavaScript.
Do you have a problem declaring that var in the next line?
You could just do:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;

Using String/Array String as Variable name in JavaScript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...
Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

Categories

Resources