Click to See Complete Forum and Search --> : heredoc strings in javascript
fozerator
06-05-2005, 05:29 PM
Hello everyone... I'm wondering if it's possible to use a heredoc type string syntax in javascript. I know I can do this:
var style = '.calendar {'
+ ' font-size:9px;'
+ ' font-family:verdana, arial;'
+ ' background-color:red;'
+ ' width:196px;'
+ '}';
But is there any way to do this?
var style = ' .calendar {
font-size:9px;
font-family:bitstream, verdana, arial;
background-color:red;
width:196px;
}';
Breaking up the string in the first method just takes a lot of time when I'm pasting a stylesheet... Just wondering if there was an easier way to do it...
-James
acorbelli
06-05-2005, 05:42 PM
To do it you need to put in a backslash to let the browser know it's continuing the string to the next line...
var style = ' .calendar { \
font-size:9px; \
font-family:bitstream, verdana, arial; \
background-color:red; \
width:196px; \
}';
Hope that helps!
fozerator
06-05-2005, 05:43 PM
Thanks anthony. That makes things a LOT easier for me :).
-James
fredmv
06-05-2005, 11:01 PM
The escapes work nicely. Another option would be to simply have it all on one line within the variable, but I suppose you care about the formatting (which, certiainly, isn't a bad thing -- code neatness is much preferred). Another thing you could do, though rather messy, would be to do something like this:<textarea id="code" style="display: none">.calendar {
font-size:9px;
font-family:bitstream, verdana, arial;
background-color:red;
width:196px;
}</textarea>Then, simply:var style = document.getElementById('code').value;
Vladdy
06-05-2005, 11:09 PM
Just out of curiousity... any good reason to put the style information in the JS code?
fozerator
06-06-2005, 07:23 AM
Nope. At least not a very good reason...
I made a calendar script that prints a variety of different calendars with different options. A few that I looked at had all of the colors hard-coded, which I really didn't like. I like to be able to add formatting options pretty quick, and CSS is a good way to do it (I learned js for programming this and some AJAX stuff, and I'm almost done with both :))
And, as far as putting the style in the JS, I decided that if I were to give the script away, it would be easier to have it all in one file... If the user doesn't like it, they can definitely move it into a seperate file, but for simplicity I decided to put it in the .js file and just add the style element to the head of the document when the script is imported....
I'm sure there are even better ways to do it, but this is my second js program, and I'm just glad it works.
Thanks for the help everyone,
-James
Vladdy
06-06-2005, 07:27 AM
It is much easier to put styles in a CSS file where they belong. It will also make much easier to change them without worrying about possible JS errors when you miss a slash. Then you put both of them in a zip along with an installation/user manual.