dynamically change LESS variables in page with JavaScript - javascript

I'm trying to use less.js to modify LESS variables dynamically with JavaScript. However, I can't seem to get it to work with modifyVars, watch, or refresh.
I tried putting the stylesheet link tag before loading less.js, using less.modifyVars({'#bg': '#00ff00'}), but no change occurs to the background. The less file I'm using is simple:
#bg: #000;
body { background-color: #bg; }
I also tried putting the stylesheet link tag after less.js, as mentioned in this question, and using less.sheets.push($('#less-link')[0]) followed by a call to modifyVars and then refresh. No change in the background color.
I also tried commenting out the #bg: #000; in the LESS file, then setting it via modifyVars. No luck: I end up with a Less::ParseError: variable #bg is undefined.
How can I dynamically change LESS variables and have the page appearance update to reflect those changes?
Edit: hm, this may be some Rails magic happening. When I loaded my less file, the variable definition was gone and all I saw was body { background-color: #000; }. When I switched to using a <style type="text/less"> block of LESS embedded in the page and used this override LESS JavaScript, I was able to change a variable with less.Override('#bg', '#00ff00') and the page's background color immediately changed. Thanks to this answer. Now I'll try it with less.js using the <style> tag instead of <link>.
Edit: looks like less-1.3.3.min.js wants LESS to be loaded in link tags--I get TypeError: Cannot read property 'href' of undefined when I try to use modifyVars and my page looks like this:
<style type="text/less">
#bg: #000;
body {
background-color: #bg;
}
</style>
<script src="/assets/less-1.3.3.min.js?body=1" type="text/javascript"></script>

Instead of doing the variable replacing client-side, since I was doing it in a Rails app anyway, I moved it server-side. I'm using the Ruby bindings for LESS to parse some LESS that includes my custom variables, rendering the parsed result with content_type: 'text/css' and using an AJAX request to add a stylesheet link to the rendered CSS.

Related

Loading a stylesheet from JavaScript memory instead of using AJAX or <link>

I am using a plugin for RequireJS which allows you to load CSS along with your JS onto the front-end.
Now, the problem is, that I don't know how to append a stylesheet to the document without using a link tag which uses AJAX to retrieve the stylesheet from the server.
define(['css!my_stylesheet_path',function(sss){
//how do I apply the stylesheet 'sss' to the document? <<<<
});
as you can see, in my RequireJS module, I have loaded a CSS file using the css plugin: https://github.com/guybedford/require-css
does anyone have any idea how to apply this stylesheet to the document directly? I assume if I use an href attribute it will go searching for the stylesheet on the server instead of using the one I already have in hand.
From this link*, it looks like I can do so like so:
var sheet = document.createElement('style')
sheet.innerHTML = "div {border: 2px solid black; background-color: blue;}";
document.body.appendChild(sheet);
Now that's some shit right there.
*http://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

Inserting CSS for an Element from a input field

Is there any easy way to take in a block of CSS from the user from an textarea and add this styling to the styling for a specific div?
See I'm creating a simple code preview tool like codePen, so far I have two textarea inputs, one for Html and one for CSS, as the user types in the Html input this updates the preview pane, this works, now I want to do it for CSS.
CSS textarea could contain a few blocks like:
h1 {
font-size:23px;
}
.myClass {
//Somestyle
}
Now I want this CSS to be contained in the
<div id="preview"></div>
So it doesnt effect the rest of the page, so a manual example would be
$('preview h1').css('font-size','23px');
Anyway to automate this?
Do it like this. Hope it works.
Add a style block for dynamic styling.
<style id="dynamicCss">
</style>
on the apply button click handler, set the style
$('#btnApplyStyle').click(function(){
$('#dynamicCss').html('').html($('#txtaCustomCss').val());
});
See the Fiddle here.
Please use developer tools to see the new style tag added to head section.
This script simply adds rule to the document. If you don't want that behavior, you can use this plugin in combination with my logic to set scope for rule. You will need to place the style tag inside of the container and add a scoped attribute to style for it to work. Please see the documentation.
If you want to use the iframe approach instead, you'll first need an HTML document to host inside of the iframe. The iframe document should be loaded for the same origin (protocol + domain) as the host document (cross-document cross-domain stuff is tricky otherwise). With your application, this is probably not an issue.
Host page:
<iframe id="preview" src="preview.html"></iframe>
To make things easier on yourself, this iframe document could load a script with convenience functions for injecting the HTML and CSS from the host.
preview.html:
<html>
<head>
<script src="preview.js"></script>
<style type="text/css" id="page-css"></style>
</head>
<body></body>
</html>
preview.js:
function setHTML(html) {
document.querySelector('body').innerHTML = html;
}
function setCSS(css) {
var stylesheet = document.querySelector('#page-css');
// Empty the stylesheet
while (stylesheet.firstChild) {
stylesheet.removeChild(stylesheet.firstChild);
}
// Inject new CSS
stylesheet.appendChild(document.createTextNode(css));
}
Now, from the host page, you can call these functions whenever your text inputs change:
document.querySelector('#preview').contentWindow.setCSS(someCSS);
This plugin may come in handy: https://github.com/websanova/wJSNova/downloads .
Edited
Insert the text of the rules in one of the existing cssStyleSheets you have.
It will be something like
window.document.styleSheets[0].insertRule("a{color:red;}",window.document.styleSheets[0].cssRules.length)
The first parameter is the rule to insert and the second is the index.
Fiddle
The only problem here is that this will affect all the DOM on the page maybe looking for a way to add the #preview before each css rule to get something like
#preview h1{}

Applying layer of JS before the HTML loads

I have a .html loaded to clients. On it, jQuery does some modifications.
The problem is that the page loads in two steps: first the original .html, then, a fraction of a second later, the modified .html.
This approach causes jerkyness. Is there a way to show the .html only once JavaScript has acted upon it?
If you MUST do this, then something like this:
Javascript:
$(document).ready(function(){
myfunction();
$("#wrapper").show();
}
CSS:
div#wrapper{ display: none; }
HTML:
<div id="wrapper">
<!-- my page stuff that i dont want to be jerky -->
</div>
However, I would raelly advise that you find a way to apply the styles/data to the page before you generate it (e.g. with PHP, ASP etc.),
You can use CSS to set default properties of the parts you are changing, if these are stylistic changes and not HTML changes.
You can also use jQuery's .load() to reload page fragments instead of the whole page.
Or, use css to set body { display: none; } and using (document).ready() to $('body').show().

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

BODY tag disappear when using Jquery.Load()

Im trying to make a pop-up like window using jquery and its modal box. First I load the content from a html file:
$("#test").load("test.htm");
Then I load the popup:
$("#test").dialog("open");
This works like it should, the content of test.html is injectet into the modal pop-up. There is only one think that is wrong, and that is the BODY tags are gone from the source of the pop-up. I need the BODY tag to be there because I do some formatting based on the BODY tag.
Does anyone know why jQuery.Load() removes the BODY tag? And are there any workarounds?
A page can only have one body tag. If you already have one on the page, the second will be ignored.
In your case, it sounds like the browser is ignoring the duplicate body (nothing specific to jquery). Rather than use the body for styling, use a containing <div> with an id or class which will be retained.
It probably removes the body tag because it's not allowed! Each document can only have one body. Rather than force everyone to redo all their HTML pages, jQuery probably just grabs the contents of the body to use when you call load().
Have you thought about perhaps wrapping everything in a containing element? eg: <div class="body"> You can then apply the exact same styles to that element.
/* change this: */
body { color: #f0f; etc }
/* to this: */
body, div.body { color: #f0f; }
You are loading the HTML into an existing document that already has a body tag. A document can only have one so it automatically filters anything and extracts only the HTML inside the body tag when using load. You should wrap your HTML in a div with a specific class and do your formatting based on that class.
From the load docs (emphasis mine):
In jQuery 1.2 you can now specify a
jQuery selector in the URL. Doing so
will filter the incoming HTML
document, only injecting the elements
that match the selector. The syntax
looks something like "url #some >
selector". Default selector "body>*"
always applies. If the URL contains a
space it should be escape()d. See the
examples for more information.
You might dynamically create the body tag using document.write of js as an alternative.
I had the same issue, and solved it more or less as the following:
instead of using load(), you can use get(), and do some smart string replacement:
var content = get("test.htm")
.replace("<body>", "<body><div class='body'>")
.replace("</body>", "</body>");
$("#test").replace($(content).filter(".body"));

Categories