How to style JavaScript created text using CSS's #font-face - javascript

I'm trying to create a page which uses java script to get data via PHP and then display it using a custom font declared in a CSS style sheet.
The entire page should use one custom font which I have declared in the main CSS file using #font-face like so:
#font-face {
font-family: 'bauhaus';
src: url('fonts/Bauhaus.woff') format('woff'),
font-weight: normal;
font-style: normal; }
My HTML file looks like this:
<html>
<head>
<script type="text/javascript" src="resources/raphael-min.js"></script>
<script type="text/javascript" src="resources/index.js"></script>
<link href="Main.css" rel="stylesheet" type="text/css">
<style type="text/css">
#canvas_container {
width: 100%;
border: 1px solid #aaa;
font-family:'bauhaus', "Times New Roman", Times, serif;
}
</style>
</head>
<body>
<div id="canvas_container">FONTTEST</div>
</body>
</html>
Within the index.js I can create text objects using Raphaeljs' syntax like so:
var txt = paper.text(150, 590, 'Test123').attr({'font-family': bauhaus, 'font-size':'70', fill:'#000'});
If I do it like that no 'Test123' text appears at all (I assume because it can't find or use the style 'bauhaus') and if I remove the font-family attribute it shows me text using the browser's default style which in my case is Arial.
The 'FONTTEST' text on the other hand is displayed correctly using the correct #font-face Font.
Now my question is how to automatically have text created by Raphaeljs (or other Javascript libraries) follow the style declared by the CSS statements? I like using custom fonts but I can't find a proper solution on how to easily use the stylized text with Javascript.
Thanks for your help!

Rather than writing out your CSS attributes in-line in your JS, why not change your CSS at the top from #canvas_container to .canvas_container , and then put the attribute "class='canvas_container' " on all of your elements which you want that font on? Should be easier to specify the class attribute than the style attribute.
An even better approach, if you want the entire page to use your font, would be to put this in your CSS (in your case, the style element):
html, body { font-family: 'bauhaus', "Times New Roman", Times, serif; }
That will make all HTML and BODY elements use your font unless later overwritten.

Well, after a bit of searching through Raphael's code I found it automatically sets its own font style (Arial) on all its text elements. I don't think that really makes sense, especially since I couldn't figure out on how to override it with a CSS '#font-face' font, but ok.
My solution was to simply delete the automatic setting of the font attribute in Raphael's source code.
For anyone interested, it's in the part where theText is declared. Just delete the font: availableAttrs.font bit in res.attrsand everything will obey the CSS style you want.

You need to register the font with cufon. See http://raphaeljs.com/reference.html#Raphael.registerFont and https://github.com/sorccu/cufon/wiki/about.

You can assign the style of your text explicitly not thinking about what really does.
Write a specific styler object function like:
function Styler( style )
{
this._style = style;
this.get = function( text)
{
return "<span style=" + this._style + "'>" + text + "</span>";
}
}
and then use everywhere:
myStyler = new Styler( 'font-size: 20px; font-weight: bold' );
...
text1 = myStyler.get( "text1" );
text2 = myStyler.get( "text2" );

Related

Can we Create CSS Selector rule with JQuery or Javascript?

we can create style or any other tag with
var st = document.createElement("style");
and even append the same to body
body.append(st);
and it will create
<body><style></style></body>
I wanna know can we put style in style tag with javascript as well not simple rules, I know there is $("selector").css() function is there which can apply css rules to selector but i want a bit more powerful rule and I want to add in style tag i just created,
something like this:
<style>
div.bar {
text-align: center;
color: red;
}
</style>
st.innerHtml or st.innerText are not letting me set these values.
Note: This was asked me to do in Browser Console only.
You can simply use jquery .text method like
const cssCode = `div.bar {
text-align: center;
color: red;
}`
$('style-tag-selector').text(cssCode)
but in my opinion, whetever your goal is - this solution is not ok. You shouldn't mess with CSS via JavaScript.
Best approach is to have styles in separately loaded .css file and then you can toggle classes to elements with javascript.
You can add your css directly within the style tag and append them to the head of your page:
$( "head" ).append( "<style>div.bar {text-align: center; color: red}</style>" );
You can append multiple style tags with css in the head beneath each other, in this way you can override previous syles, but it is not best practice.
I prefer having your styles in separate files and to manage wether or not the files will be included in your code.
Actually there's an interface for this. For example, add a style element and add a rule to it (this will result in anything with the class should-be-red to be red.
var styleElement = document.createElement('style');
document.head.appendChild(styleElement);
var sheet = styleElement.sheet;
sheet.insertRule('.should-be-red { color: red; }', 0);
You can iterate over the rules and insert/delete rules and exciting things like that.
More info: https://developer.mozilla.org/en-US/docs/Web/API/CSSStylesheet
jsbin: https://jsbin.com/jodiro/1/edit?html,js,output

Specify font from font file in SVG using svg.js

For a web project, I'm using SVG with the svg.js library to make my life easier. The svg.js library works perfectly and generates correct SVG so I'm pretty sure everything is working OK on that front.
For this project, I can refer to a font like this in my CSS file:
#font-face {
font-family: 'FreeUniversal';
src: url('../fonts/freeuniversal-regular.ttf');
font-weight: normal;
font-style: normal;
}
This font is then picked up correctly and displayed for various elements in my HTML code.
My question is how I can do this in SVG using the svg.js library? I understand I can set the current font and so on, like this:
sCurrentSvgShape.attr({
'font-family': inFontName,
'font-size': inFontSize });
And this works for web-safe fonts like "Helvetica" or "Courier" or "Sans". But I want to know how I can set a font family that refers to my specific font file, just as I can in CSS.
I understand CSV has syntax to do this, such as:
<defs>
<style type="text/css">
<![CDATA[
#font-face {
font-family: Delicious;
src: url('http://nimbupani.com/demo/svgfonts/delicious-roman.otf');
}
]]>
</style>
</defs>
So, what's the best way to include this in svg.js? Do I have to create these "defs" nodes manually in some fashion? Is there support from the library to accomplish this?
There is no special method to accomplish that in svg.js. However you could make use of the bare element which lets you include non supported elements such as style.
You would use this in the following way:
root.defs().element('style').words(
'#font-face {' +
'font-family: Delicious;' +
'src: url(\'http://nimbupani.com/demo/svgfonts/delicious-roman.otf\');' +
'}'
)
I did not test it but that should do it.
The second possibility is to invent this style element with the invent method and include this functionality into svg.js yourself.
It would look something like this:
SVG.Style = SVG.invent({
// Initialize node
create: 'style'
// Inherit from
, inherit: SVG.Element
// Add class methods
, extend: {
font: function(){
// code to add a font to the style tag
}
, rule: function(){
// code to add a style rule... whatsoever
}
}
, construct: {
// Create a style element
style: function() {
return this.put(new SVG.Style)
}
}
})
This would be used like so:
root.defs().style().font('your font method to add a font').rule('add another css rule')

jQuery height() for an element containing a custom-font text seems inconsistent

We have a single div like this:
<body>
<div class="styled">
Text
</div>
</body>
And our style looks something like:
#font-face {
font-family: 'Liberation Mono'; /*a name to be used later*/
src: url('LiberationMono-Regular.ttf'); /*local URL to font*/
}
.styled {
font-size: 200px;
font-family: "Liberation Mono";
}
Now, if we add some Javascript to be executed on document ready (after including jQuery 2.1.4):
<script>
$(document).ready(function() {
console.log($("div.styled").height())
});
</script>
The value displayed is the console is 243, but inspecting the div with the developper tools, it is actually 227px high.
Using the default font from the browser (Chrome in our case), the result would be consistent.
Is this expected behaviour ?
Is there a known work around ?
EDIT: The font is available for download from Font Squirrel.
This is because custom fonts aren't loaded at $.ready. You need to listen to the $(window).load() event instead.

changing text font through css for specific text in d3

I am using the d3 framework and I am trying to specify the font the following element using css (I want to use a custom font, that is why I am using css).
var anchorNode = svg.selectAll("g.anchorNode").data(force2.nodes()).enter().append("svg:g").attr("class", "anchorNode");
anchorNode.append("svg:circle");
anchorNode.append("svg:text").text("test");
I tried using
text {
font: 2px Arial;
pointer-events: none;
}
but this does not work for this specific text. I am assuming it is because the text is appended to the node. What would be the correct syntax to access the text in css?
Do you have a link to the rendered HTML or a jsfiddle?
It looks like your appending a class called anchorNode. You could possibly updating the CSS font for that class:
.anchorNode {
font-family: "Times New Roman", Times, serif;
font-size: 2px;
}

Changing media specific CSS properties from Javascript

I have a CSS property (font) that I need to be able to change from Javascript (a pulldown). However, this font should only be used when printing (#media print).
So, the javascript can't just change the value of the font, because that will effect the screen view as well. Is there a way to change ONLY the print version of the font property?
Alternatively is there a way to have a CSS property be a reference to another property?
That way, in the print CSS, I could say font:printfont, and in the screen CSS font:12. And then change the value of printfont, and it would only change the font when printing.
thanks.
EDIT: The point is that I need to be able to change the font size that the document gets printed at from the pulldown, but I don't want to change the font size that the document gets displayed at.
That's an interesting dilemma you have going on there. Off the top of my head, the only thing I can think of is to add a new tag to the header where your font-size is declared with !important. For example, in your head tags:
<style type="text/css" media="print">
.printfont {
font-size: 16px !important;
}
</style>
This will ensure that the new font-size will take precedence.
The following is a very quick example of how you may accomplish this with javascript
<script type="text/javascript">
var inlineMediaStyle = null;
function changeMediaStyle ()
{
var head = document.getElementsByTagName('head')[0];
var newStyle = document.createElement('style');
newStyle.setAttribute('type', 'text/css');
newStyle.setAttribute('media', 'print');
newStyle.appendChild(document.createTextNode('.printFont { font-size: 16px !important;}'));
if (inlineMediaStyle != null)
{
head.replaceChild(newStyle, inlineMediaStyle)
}
else
{
head.appendChild(newStyle);
}
inlineMediaStyle = newStyle;
}
</script>
Just ensure that you have onchange="changeMediaStyle()" as an attribute on your dropdown. Also, as a disclaimer in my example, I am not accounting for things like memory leaks, so you will have to work out those kind of issues on your own.
As to your alternate question, as far as I am aware, there isn't any method for declaring/using what is essentially CSS variables. However, there is currently a recommendation out there for it: http://disruptive-innovations.com/zoo/cssvariables/
seems like what you want to do is myabe just change or add a class to the item with JS
<p class="inrto comicSans">this is the text to change</p>
#screen p.intro {font-family:verdana;}
#print p.comicSans {font-family:comic-sans;}
You could just use JavaScript to switch classes, and have the
#print {
.myPrintClass { font-family: serif; }
}
#screen {
.defaultClass { font-family: sans-serif; }
}
While the class-based solutions would totally work, you could also use Javascript to dynamically add a new <link> tag to the page. For instance, if you have:
stylesheet1.css:
#print * {font-family:verdana;}
stylesheet2.css:
#print * {font-family:comicSans;}
You could then use jQuery to do something like:
$(document.body).append("<link href='stylesheet2.css'/>");
(you could do it without jQuery too, but I forget that syntax and am too lazy to look it up ;-)).
However, if you're only changing small amounts, a single stylesheet + different classes is probably the better way to go; the new <link> tag solution is only worthwhile if you have a bunch of different style changes happening.

Categories