javascript font size not working - javascript

why this don´t work:
function rp_insertTable() {
FM_log(3,"rp_insertTable() called");
var farmTable = dom.cn("table");
var ftableBody = dom.cn("tbody");
var i;
var maximize = GM_getValue("Maximize_" + suffixGlobal, 0);
farmTable.className = "FMtbg";
farmTable.id = "farmMachineTable";
farmTable.setAttribute('cellpadding', 2);
farmTable.setAttribute('cellspacing', 1);
farmTable.style.marginBotton = "12px";
farmTable.style.font = "bold 12px arial,serif";
the font does change in format, but the font size is not working, I can put 100px and it deosn´t change anything, why is that?

Why don't you try doing:
farmTable.style.fontSize = "12px"; ?

Accordingly XHTML.com your syntax is off:
Edit, more descriptive: You missed the font-style property in the list, you only had font-weight.
http://xhtml.com/en/css/reference/font/
Also, font is a shorthand, if you just want to set one indeed use the fontSize property.
It probably changes because your font is now no longer well-formed CSS and it sets it back to default.

Related

Set width of ace editor instance according to the length of characters in it

I am working on the project where I have created a custom Rich Text Editor using contenteditable attribute. In this rich text editor I want insert single line ace editor instance of which width will be set according to the number of characters in it.
For restricting the ace editor instance to single line I have handled the "Enter" key event which does not let the ace instance to insert new line.
var editor = ace.edit(script_editor);
editor.commands.on("exec", function (e) {
editor.container.querySelector(".ace_content").style.transform = "none";
if (e.args && e.args.charCodeAt(0) == 10) {
e.preventDefault();
e.stopPropagation();
console.log("vdgscript-mode.js")
}
});
Now, the problem I am facing is that I want the ace instance width to adjust according to the number of character in it instead to have full width.
For that I am taking a canvas object and calculating the width of the text. But the problem with this code is, it is giving me the expected width on every key press but the css left property of the ace editor does not stay '0px' which makes the text in the ace editor instance to hide at the left side.
Code for setting the width is as follows:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "15px sans-serif";
var width = ctx.measureText(code).width;
editor.container.style.width = (width + 3) + "px";
Actual Result: .
Expected Result: .
The black in the below image the ace instance in which I have entered an array.
you can use a method similar to the one used by the tree rename editor in cloud9 https://github.com/c9/core/blob/master/plugins/node_modules/ace_tree/lib/ace_tree/edit.js
<style>
#inlineEditor {
display: inline-block;
vertical-align: middle;
}
</style>
<div>inline editor <span id=inlineEditor>txt</span></div>
<script src=https://ajaxorg.github.io/ace-builds/src-noconflict/ace.js>
</script>
<script>
var inlineEditor = ace.edit("inlineEditor", {
maxLines: 1,
showGutter: false,
showPrintMargin: false,
theme: "ace/theme/solarized_light",
})
// make cursor movement nicer for
inlineEditor.renderer.screenToTextCoordinates = function(x, y) {
var pos = this.pixelToScreenCoordinates(x, y);
return this.session.screenToDocumentPosition(
Math.min(this.session.getScreenLength() - 1, Math.max(pos.row, 0)),
Math.max(pos.column, 0)
);
};
inlineEditor.renderer.on("beforeRender", updateSize)
function updateSize(e, renderer) {
var text = renderer.session.getLine(0);
var chars = renderer.session.$getStringScreenWidth(text)[0];
var width = Math.max(chars, 2) * renderer.characterWidth // text size
+ 2 * renderer.$padding // padding
+ 2 // little extra for the cursor
+ 0 // add border width if needed
// update container size
renderer.container.style.width = width + "px";
// update computed size stored by the editor
renderer.onResize(false, 0, width, renderer.$size.height);
}
updateSize(null, inlineEditor.renderer)
</script>

random background color generator with pure javascript (no jquery)

var color;
function randomColor() {
color = '#' + Math.random().toString(16).slice(2, 8); // Random number converted to hexadecimal with toString(16) and then slice to make it a 6 digit number. like fe2e4d or f4e22e
};
var change = document.getElementById('color_change');
change.addEventListener('click', function() {
document.getElementById('random_background').style.backgroundColor = "color" ;
});
div{
width:300px;
height:300px;
}
<div id="random_background"></div>
<button id="color_change" >Color Change</button>
I think the last part is where the problem lies, but i am not able to find anywhere how to implement it correctly. Please help.
As stated by #Teemu in the comments, you are setting a string to the backgroundColor property instead of setting the actual value of the color variable.
Here goes an example that will help you, without the use of the var color;
make your randomColor() function return the value directly. Then call that function in the backgroundColor property, see below:
function randomColor() {
return '#' + Math.random().toString(16).slice(2, 8);
};
var change = document.getElementById('color_change');
change.addEventListener('click', function() {
document.getElementById('random_background').style.backgroundColor = randomColor();
});
div{
width: 300px;
height: 150px;
}
<div id="random_background"></div>
<button id="color_change" >Color Change</button>
If you want to use the var color, then call randomColor() before set the backgroundColor property, and then set it as a variable, not a string:
...
randomColor();
document.getElementById('random_background').style.backgroundColor = color;
"div" has nothing height when is blank
you should initialize height to your div.
also use correct variable for color.
good luck
Here a solution using random numbers for each triplet:
function rT(){
//random number between 0 and 255
//you could change the limits or pass a parameter to this function
return Math.floor(Math.random() * (255 - 0)) + 0;
}
var change = document.getElementById('color_change');
change.addEventListener('click', function() {
document.getElementById('random_background').style.backgroundColor = "rgb("+rT()+" "+rT()+" "+rT()+")"; });
//in this case we use this form rgb(0-255,0-255,0-255)
Full example here: https://jsfiddle.net/ztavxrse/
Changing the limits https://jsfiddle.net/c5j6fpnL/

JavaScript filter hueRotate does not work

I am trying to change an image's (#bgImage) hue when hovering over a button (profIcon) in JavaScript. This type of button is created with JS, and there are 9 of them.
Here is the code that creates a DOM image element, sets it's source, position, size and transition. Finally it appends it to it's container. The image appears correctly, where it should be.
I am using quickID in place of document.getElementById, and it is working without error.
var bgImage = document.createElement("img");
bgImage.id = "bgImage";
bgImage.src = "./resources/images/backgrounds/profession/selector.jpg";
bgImage.style.position = "absolute";
bgImage.style.left = "0px";
bgImage.style.top = "0px";
bgImage.style.width = "100%";
bgImage.style.height = "100%";
bgImage.style.zIndex = 1;
bgImage.style.webkitTransition = "all 0.5s ease";
quickID("centerdiv").appendChild(bgImage);
Here is the code that runs when I hover over an image:
profIcon.onmouseover = function () {
var thisNr = this.id.substr(8); //last char of the profIcon ID; number between 0 and 8
var newHue = profTomb[thisNr][3]; //this contains the value and only that.
console.log(newHue); //always returns the correct value
quickID(this.id).style.webkitFilter = "grayscale(0%)"; //this part works, too
quickID("bgImage").style.webkitFilter = "hueRotate(" + newHue + "deg)";
}
My problem: for some reason, the filter does not apply. newHue is either a positive (75), or a negative (-23) value and it's inserted correctly, as it appears in the console log. I only use webkit vendor prefix as I use Google Chrome.
I waited up to 1 minute with my mouse cursor over the image, thinking my system needs time to process the transformation, but nothing happened.
Does anyone knows what is the problem?
The correct string to use is hue-rotate, not hueRotate. The following should work:
quickID("bgImage").style.webkitFilter = "hue-rotate(" + newHue + "deg)";

Size of character in pixels

I am trying to create text box in the HTML5 canvas, I know you can't actually do this, so I am creating a box and creating some text at the same location. But, I want to make sure the text stays in the box so I need to know when part of the text is extending out of the box. I figure I should be able to measure the text in terms of pixels and then compare it to the box. My question is, using javascript, how can I measure the size of the characters for any given font?
You can use context.measureText to get the width of your specified text:
// set the font
context.font = "14px verdana";
// use measureText to get the text width
var textWidth = context.measureText("Measure this!").width;
Text wrap would look something like this:
function wrapText(context, text, x, y, maxWidth, fontSizeFace) {
var words = text.split(' ');
var line = '';
var lineHeight=measureTextHeight(fontSizeFace);
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if(testWidth > maxWidth) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
}
You can use as markE mention in his answer the measureText() function.
The specifications defines its result (a TextMetrix):
interface TextMetrics {
// x-direction
readonly attribute double width; // advance width
readonly attribute double actualBoundingBoxLeft;
readonly attribute double actualBoundingBoxRight;
// y-direction
readonly attribute double fontBoundingBoxAscent;
readonly attribute double fontBoundingBoxDescent;
readonly attribute double actualBoundingBoxAscent;
readonly attribute double actualBoundingBoxDescent;
readonly attribute double emHeightAscent;
readonly attribute double emHeightDescent;
readonly attribute double hangingBaseline;
readonly attribute double alphabeticBaseline;
readonly attribute double ideographicBaseline;
};
The problem however is that only width is implemented in the major browsers so you cannot get the height (ascent + descent) with this function yet (and I wouldn't be surprised if a canvas based word processor from at least one of the "major 3" shows up right before this gets fully implemented... but that's a regression and a speculation :-) ).
In order to measure the font you will have to use a DOM element, and this little trick will allow you to measure a font's width and height:
Online demo here (open console to see result).
function measureText(font, txt) {
var el = document.createElement('div'),
cs, res;
el.style.cssText = 'position:fixed;left:-4000px;top:-4000px;padding:0;margin:0;font:' + font;
el.innerHTML = txt;
document.body.appendChild(el);
cs = getComputedStyle(el);
res = {width: cs.getPropertyValue('width'),
height: cs.getPropertyValue('height')};
document.body.removeChild(el);
return res;
}
The function creates a div element, applies some basic styles to it to place it outside window. This is because we have to attach it to the DOM tree in order to use getComputedStyle() - we also have to get the property values before we remove the element again.
Pass arguments for font as you would with the context (ie. 20px sans-serif) and the text.
It comes with a small performance penalty obviously (though using fixed positioned elements won't cause any re-flow so it's not so bad) so use sparsely.

svg appending text element - gives me wrong width

i'm appending a text element to a svg via javascript. After appending i wanna set x and y coordinate, however, it returns me the wrong width of the text element when using it to calculate x.
Interesting:
In Chrome, when actualize the page via F5 or button it returns wrong width, when pressing enter in the adress bar, the width is right - strange!
Here is the small code:
var capt = document.createElementNS("http://www.w3.org/2000/svg", "text");
// Set any attributes as desired
capt.setAttribute("id","capt");
capt.setAttribute("font-family","Righteous");
capt.setAttribute("font-size","30px");
capt.setAttribute("fill", "rgb(19,128,183)");
var myText = document.createTextNode(this.options.captTxt);
capt.appendChild(myText);
this.elements.jSvgElem.append(capt);
capt.setAttribute("x", this.options.windowWidth-this.options.spacer-document.getElementById("capt").offsetWidth);
capt.setAttribute("y", this.options.captY+$('#capt').height());
OK, the problem seems to be that the browser doesn't calculate the correct width when using an other font. Not setting a font results in a correct width.
I solved the problem by setting the reference point ("alignment-point") to the upper right corner ot the text element by setting attributes:
capt.setAttribute("text-anchor", "end");
capt.setAttribute("alignment-baseline", "hanging");
This way i do not have to subtract the width and add the height of the element!
There is a bug:http://code.google.com/p/chromium/issues/detail?id=140472
it just pre init some functions that calculates text width so you should call this function before(i'm sure that there is several extra lines that can be deleted):
fixBug = function () {
var text = makeSVG("text", { x: 0, y: 0, fill: "#ffffff", stroke: '#ffffff'});
text.textContent = "";
var svg = $("svg")[0];
svg.appendChild(text);
var bbox = text.getBBox();
var Twidth = bbox.width;
var Theight = bbox.height;
svg.removeChild(text);
}
$("svg") - Jquery selector

Categories

Resources