Assign var as a selector - javascript

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);
});
}

Related

selecting multiple classes in jQuery and find element width on this instance

I tried searching for two hours but couldn't find the exact answer.
I am trying to do the following:
function myFunction() {
$('.class1, .class2').each(function (){
var Width1 = $(this).find('.class1').width();
var Width2 = $(this).find('.class2').width();
// do stuff here...
});
}
I want to select two classes, then retrieve width of the elements of the current instance to two different variables, there are thousands of elements with class1 and class2. Class 2 is not a subclass of Class 1, selection seems to be valid, but vars are undefined after execution, why is it not working?
As you said .class1 is not child of .class2 so .find wont work. You need to check if current element is class1 then assign its value to width1 other assign value to width2. Use .is() to do this:
function myFunction() {
$('.class1, .class2').each(function (){
var Width1, Width2;
if($(this).is(".class1"))
Width1 = $(this).width();
else
Width2 = $(this).width();
});
}

How to re-size constantly changing text to fit in a div with a fixed width, based on the changing of a <select>?

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>

Giving specific css with jquery for each instance of div depending on text height

I have a grid with several boxes (280px by 280px)and I need to vertical align text enclosed on hover overlays.
My code is working for first element but txt lenght/height varies on each box and I need a function that assigns top padding depending on specific p height.
I believe I can use .each , but I wasn't able to implement it successfully.
Here is my working code that I need to modify to target each box individually:
var txtHeight = $( ".login-item .lgn-overlay p" ).height();
var topPadding = ((284 - txtHeight) / 2);
$('.login-item .lgn-overlay').css('padding-top', topPadding);
$('.login-item .lgn-overlay').each(function(){
var $this = $(this);
$this.css('padding-top', function(){
return ((284 - $this.find("p").height()) / 2);
});
});
Try if this works. I made this on plan page so correct if any error in the code
Try something like this
//determine this programmatically
var necessaryHeight = 200;
$('.login-item .lgn-overlay').each(function () {
//this = each individual element
//$this = a jQuery wrapper for the given element.
var $this = $(this);
//The rest I think you understand
var thisHeight = $this.outerHeight();
var missingHeight = necessaryHeight - thisHeight;
var addedPadding = missingHeight / 2;
$this.css('padding-top', addedPadding);
});

How To Get Font Size in HTML

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.

How to determine the top element?

I have a complex structure of many nested, absolutely positioned elements.
These elements may or may not have their z-index set.
They also may or may not have the same parent element.
I am wondering what is the best / simplest way to return which element is on 'top'. Something like the following...
$(".panel").topMost()
Thanks (in advance) for your help
Do you mean the element with highest z-index:
$(document).ready(function() {
var array = [];
$("*").each(function() {
array.push($(this).css("z-index"));
});
var highest = Math.max.apply(Math, array);
console.log(highest);
});
A plugin is there ..topZindex
$.topZIndex("div");
Try this:
var z = [];
$('.panel').each(function(i, el) {
var $panel = $(el),
zindex = $panel.css('z-index');
z[zindex] = $panel;
});
var topMost = z.slice(-1);
See if you don't specify z-index to absolute elems then last of the element will be on top of other elems, means last element will have a greater highest default z-index calculated by browser itself.
Try this fiddle: http://jsfiddle.net/fLB2W/
var array = [];
$("*").each(function () {
if ($(this).css('position') == 'absolute') {
array.push($(this).css("position")+'<--pos & class -->'+$(this).attr('class'));
}
});
console.log(array[array.length-1]);
I faced similar issue with Modal dialog while displaying jQuery UI datepicker and using event parameters to figure out the clicked icon. Modal dialog overlay was preventing the new datepicker from showing on top of the modal dialog.
The best solution worked in three browsers (IE, Firefox, and Chrome) is:
function topZIndex(target, selector) {
var objs = $(target).parents(selector + '[z-index > 0]');
var a1 = -1;
$.each(objs, function (index, z1) {a1=(z1.style.zIndex > a1)? z1.style.zIndex : a1; });
return a1;
};
using event parameters as follows:
var zIndex = topZIndex(event.currentTarget, 'div')+1;
or
var zIndex = topZIndex(event.currentTarget, '*')+1;
Both combinations will generate same result, however it is more efficient to be specific by specifying 'div' instead of '*'
Then assuming my date picker id is datepickerpanel to set the new zIndex for datepicker
$('#datepickerpanel').css('z-index', zIndex);
This solution provides proper z-index value to place the new object on top of modal dialog.

Categories

Resources