I was reading a question on here trying to get the font size of a text. The answer they gave was to get the pixel size using a measure method. All i want to be able to do is get the font size value so i can change it.
For example:
var x = document.getElementById("foo").style.fontSize;
document.getElementById("foo").style.fontSize = x + 1;
This example does not work though these two do
document.getElementById("foo").style.fontSize = "larger";
document.getElementById("foo").style.fontSize = "smaller";
The only problem is that it only changes the size once.
Just grabbing the style.fontSize of an element may not work. If the font-size is defined by a stylesheet, this will report "" (empty string).
You should use window.getComputedStyle.
var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
// now you have a proper float for the font size (yes, it can be a float, not just an integer)
el.style.fontSize = (fontSize + 1) + 'px';
If your element don't have font-size property your code will return empty string. Its not necessary that your element should have font-size property. The element can inherit the properties from parent elements.
In this case you need to find the computed font-size. Try this (not sure about IE)
var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize;
console.log(computedFontSize);
The variable computedFontSize will return with the font size with unit. Unit can be px, em, %. You need to strip out the unit to do an arithmetic operation and assign the new value.
If you are using Jquery than following is the solution.
var fontSize = $("#foo").css("fontSize");
fontSize = parseInt(fontSize) + 1 + "px";
$("#foo").css("fontSize", fontSize );
Hope this will work.
Making it work for every case
Sometimes (when using media queries for instance) the above answers don't work, here is how to achieve it anyway:
const fontSize = window.getComputedStyle(el).fontSize
The value that you are getting from fontSize is something like "12px" or "1.5em", so adding 1 to that string will result in "12px1" or "1.5em1". You can take the font size and manipulate it with:
var fontSize = parseInt(x);
fontSize = fontSize + 1 + "px";
document.getElementById("foo").style.fontSize = fontSize;
if the html element has inline style, you can using the .style.fontSize to get the font-size!
when the html element doesn't has inline style, you have to using the Window.getComputedStyle() function to get the font-size!
here is my demo codes!
function tureFunc() {
alert(document.getElementById("fp").style.fontSize);
console.log(`fontSize = ${document.getElementById("fp").style.fontSize}`);
}
function falseFunc() {
alert( false ? document.getElementById("fh").style.fontSize : "check the consloe!");
console.log(`fontSize = ${document.getElementById("fh").style.fontSize}`);
}
function getTheStyle(){
let elem = document.getElementById("elem-container");
let fontSize = window.getComputedStyle(elem,null).getPropertyValue("font-size");
// font-size !=== fontSize
console.log(`fontSize = ${fontSize}`);
alert(fontSize);
document.getElementById("output").innerHTML = fontSize;
}
// getTheStyle();
<p id="fp" style="font-size:120%">
This is a paragraph.
<mark>inline style : <code>style="font-size:120%"</code></mark>
</p>
<button type="button" onclick="tureFunc()">Return fontSize</button>
<h3 id="fh">
This is a H3. <mark>browser defualt value</mark>
</h3>
<button type="button" onclick="falseFunc()">Not Return fontSize</button>
<div id="elem-container">
<mark>window.getComputedStyle & .getPropertyValue("font-size");</mark><br/>
<button type="button" onclick="getTheStyle()">Return font-size</button>
</div>
<div id="output"></div>
reference links:
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
It's simple yet helpful! Replace el as needed.
window.getComputedStyle(document.querySelector('el')).fontSize;
Update:
Using Developer tools like in Chrome. It's better.
Please see images attached.
Try this it would definately help you in determining the font size
var elem = document.createElement('div');
var t=document.createTextNode('M')
elem.appendChild(t);
document.body.appendChild(elem);
var myfontSize = getStyle(elem,"fontSize")
alert(myfontSize)
document.body.removeChild(elem);
function getStyle(elem,prop){
if (elem.currentStyle) {
var res= elem.currentStyle.margin;
} else if (window.getComputedStyle) {
if (window.getComputedStyle.getPropertyValue){
var res= window.getComputedStyle(elem, null).getPropertyValue(prop)}
else{var res =window.getComputedStyle(elem)[prop] };
}
return res;
}
we can further use getter and setter to determine if fontsize is changed afterwards by any peice of code
Here is how you get the top-level font-size (associated to html tag):
window.getComputedStyle(document.getElementsByTagName('html')[0]).getPropertyValue('font-size');
It's useful to check if it's the default 16px or not.
Related
Ok.. So i have a html element that displays a current value, value is changed via range slider, i change the value of the html element using javascript with the following code:
hex_out = document.querySelector('#hex');
hex_out.value=rangeValue;
Which the above works fine, but recently I've needed to be able to add a bit of html code into hex_out.value
for example if i try
hex_out.value="<font color='red'>"+rangeValue+"</font>"
it will change hex_out.value to the code shown below
<font color='red'>Range slider value</font>"
which is obviously not what i'm trying to accomplish. How would i add html code to hex_out.value and have it display correctly?
Before anyone trys to say "This is a duplicate question", realize i've tried nearly ALL solutions shown on stack overflow with no luck
You'll need to modify the color via the element's style property. Try the following:
hex_out.style.color = 'red';
If you need to add any HTML, then (assuming that the hex_out element is a container element, and not an <input> tag), you can assign the HTML to its innerHTML property like so:
hex_out.innerHTML = '<strong>This is a <em>formatted</em> value.</strong>';
Another edit: It looks like you're using an <output> element, which doesn't accept child elements as far as I know. In this case, you'll likely want to use a regular <div> or <span> tag instead of <output> and then update its value manually as your sliders move using the innerHTML property described above.
I think you are looking for something like this:
var hex_out = document.querySelector('#hex'),
rangeValue = document.querySelector('#val');
rangeValue .addEventListener('input', function () {
hex_out.innerHTML = "<font color='red'>"+rangeValue .value+"</font>";
}, false);
<input type=range id=val>
<span id=hex>50</span>
Your difficulty arose because you put an obsolete font tag in the output tag which only accepts "phrasing content". The font tag is not supported in HTML5 and not on the list of phrasing content elements.
As #Mark said, a simple div will do if you require HTML to be rendered.
The example you gave is the thing normally expecting from javascript. I consider you want to change html of an existing element not value. If it is you can use below code:
hex_out. innerHTML ="<font color='red'>"+rangeValue+"</font>"
Existing fiddle link JSFiddle
Tested and works:
function setColor() { debugger;
Rval = parseFloat((r_out.value / 255.00).toFixed(3));
Gval = parseFloat((g_out.value / 255.00).toFixed(3));
Bval = parseFloat((b_out.value / 255.00).toFixed(3));
hex = "R: " + Rval + " " + "G: " + Gval + " " + "B: " + Bval;
var r_hex = parseInt(r.value, 10).toString(16),
g_hex = parseInt(g.value, 10).toString(16),
b_hex = parseInt(b.value, 10).toString(16),
hex1 = "#" + pad(r_hex) + pad(g_hex) + pad(b_hex);
body.style.backgroundColor = hex1;
hex_out.innerHtml = hex + [
'<br/><font size="1px">GSC RGB Selector</font>'
].join('#hex');
}
I have a var named as sliceText which contains a text which is collected whenever user hover over the section of a visualforce chart. I'm trying to increase the size of this text with a value which gets calculated at run time and newSize var hold the same. But using jquery following syntax is not working and I'm not able change the font size.
var sliceText = j$(this).text();
j$(sliceText).css('font-size', newSize);
How can I assign a var as a selector using jquery? I want following solution work for me but its NOT when I tried to!! https://docs.acquia.com/articles/increase-text-size-jquery
You need to apply css to the DOM object containing the text no the text
j$('path, tspan').mouseover(function(e) {
j$(this).children().css('font-size', 15);//reset to default size font
j$(e.target).css('font-size', newSize);
});
You didn't mentioned whether the dom is an id or a class
var sliceText = j$(this).text();
j$("#"+sliceText).css('font-size', newSize); --- if the dom element is an id
j$("."+sliceText).css('font-size', newSize); --- if the dom element is a class
var newSize = '30px';
var originalSize = '14px';
$("span").hover(function(){
$(this).css('font-size', newSize);
}, function(){
$(this).css('font-size', originalSize);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span> Jan </span><br/>
<span>Feb</span><br/>
<span>March</span>
As i understand you want to change the font size of hover element
so try this one
function funtest()
{
var oldSize = parseFloat(j$('text').css('font-size'));
var newSize = oldSize * 2;
j$('path, tspan').mouseover(function () {
j$(this).css('font-size', newSize);
});
}
Currently I am doing something like this:
function newFont(newSizeA, newSizeB) {
var elem = document.getElementById('style-1');
if (typeof(elem) != 'undefined' && elem != null) {
removeChildNodes(elem); // function that removes child
nodesremoveNode(elem);
}
var styleText = ".a { font-size:" + newSizeA + "px; } .b { font-size:" + newSizeB + "px; }";
var x = document.createElement('style');
x.setAttribute("type", "text/css");
x.setAttribute("id", "style-1");
if (x.styleSheet) { // for IE
x.styleSheet.cssText = styleText;
}
else { // others
var textnode = document.createTextNode(styleText);
x.appendChild(textnode);
}
}
The point of it is that there is a loop happening and another function is measuring the size of a menu to make sure it fits in a spot when someone is changing the font size.
I am wondering, is there a better way to create and manipulate elements? I need to change padding and font size but right now as you can see I'm just removing it entirely and recreating it.
I think the easiest way is to prepare several css-styles for different font-sizes and then attach them as so:
function newFont(targetElement, fontSize) {
document.getElementById(targetElement).className = fontSize;
}
newFont('myElement','bigFont');
the css-style would then be:
.bigFont {
font-size: 5em;
}
if you want to add the style do:
document.getElementById("MyElement").className += "MyClass";
if you want to remove styles or check if the style is already apllied please refer to this perfect answer:
Change an element's class with JavaScript
So I have text that changes whenever a specific <select> is changed to a different option. I need to make this text change font-size based on if it flows to the outside of the div. Here's what I have so far:
var autoAdjust = {
init:function(){
var eObject = document.getElementById('select');
eObject.on( "change", autoAdjust.task );
},
task:function(){
var divWidth = jQuery(".containerDiv").width();
var text = document.getElementById("text");
var fontSize = 16;
while (text.width() > divWidth){
text.css("font-size", fontSize -= 0.5);
}
}
}
autoAdjust.init();
Here's the CSS:
/* This makes it so you can measure the text width */
#text{
white-space:nowrap;
display: inline-block;
}
How would I make this work?? I feel like I'm over complicating it.
The text variable contains a javascript dom object, not a jQuery object. This matters because .text() and .css() are both jQuery methods and do not work (are undefined) on plain dom objects. Your code should function correctly like so:
var autoAdjust = {
init:function(){
var eObject = jQuery('select');
eObject.on( "change", autoAdjust.task );
},
task:function(){
var divWidth = jQuery(".containerDiv").width();
var text = jQuery("#text");
var fontSize = 16;
while (text.width() > divWidth){
text.css("font-size", "-=0.5");
}
}
}
autoAdjust.init();
Shooting from the hip here, but it looks like there are a couple problems with the snippet.
Dom elements don't natively support the "on" method. You'll need to use a library selector to get "on" support (ie jQuery, etc)
You need to specify the unit type to increase/decrease font size.
See snippet with suggested edits (untested, but the spirit of the edits are evident)
<select id="MySelect">
...
</select>
<div class="containerDiv">
<span id="MyText"></span>
</div>
<script type="text/javascript">
var autoAdjust = {
init:function(){
var eObject = $("#MySelect"); // jQuery selector (using ID)
eObject.on( "change", autoAdjust.task );
},
task:function(){
var divWidth = $(".containerDiv").width(); // jQuery selector (using class)
var text = $("#MyText"); // jQuery selector (using ID)
var fontSize = 16;
while (text.width() > divWidth){
text.css("font-size", (fontSize -= 0.5) + "px"); // specify units
}
}
}
autoAdjust.init();
</script>
How can I be sure the text in the input box, the number of pixels from the left box? It may have utf8, Chinese
This might not be the best way, but i guess this can be a start. This will return the number of pixels remaining in the input element:
function getRemainingWidth(element){
var span = $('<span class=\"'+$(element).attr('class')+'\" style=\"visibility:hidden;\">'+$(element).val()+'</span>');
$(document.body).append(span);
var diff = $(element).width() - $(span).width();
$(span).remove();
return diff;
}
One way to do it is creating a span element and adding your text to it. But there is a catch: you have to add it to the dom in order get its with:
var sYourText = 'asdfafdsa, dzcvxvxc';
var oText = document.createElement('span');
oText.innerHTML = sYourText;
document.getElementsByTagName('body')[0].appendChild(oText)
console.log(oText.offsetWidth);
Of course: be sure to apply the same font that your textarea have.
$("textarea").keyup(function(){
var s = $(this).val()
var data = s.replace(/(\s)/g,' ')
console.log(data)
$('span').html(data)
})
I replace it with a regular spaces replaced, but wrapping problems that may require using CSS