Converting Percent value to pixel in JavaScript or JQuery - javascript

I have a string value in percent unit that will be assign to height but before assigning I need to deduct another height which got by top() the output result is NaN, My code is as below:
var valHeight = "50%";
var result = valHeight - $("#item").css("top");
$("#AnotherItem").height(result);
as valHeight is string and percent and height is pixel the result will be NaN. How may I solve that issue? the valHeight is percent but top value is pixel. I need to have my result as percent
Let's clarify more:
I want to use calc function of CSS and I guess the below code is correct:
$('#AnotherItem').css('height', valHeight).css('height', '-='+itemOffsetTop);
the only problem is I want to use subtracted value in animate function.

First
valHeight is a string you need to convert that to number.
var varlHeight = parseInt("50px");
Second
Your $("#item").top() is invalid, use this instead.
$("#item").offset().top
Putting them together
var valHeight=parseInt("50px");
var result= valHeight - $("#item").offset().top;
$("#AnotherItem").height(result);
Update
Since you've updated your post with a '50%' value. How about doing this kind of approach instead.
var valHeight="50%";
var itemOffsetTop = $("#item").offset().top;
$('#AnotherItem').css('height', valHeight).css('height', '-='+itemOffsetTop);

I see two issues with your code:
valHeight is a string, not a number. It needs to be a number before using it in a math operation.
It's also not clear where you're getting .top() from. Perhaps you meant to use .offset().top?
Example:
var valHeight = 50;
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");
Now, you modified your question to use 50% and it doesn't really make sense. If you want the result to be 50% of $("#item").offset().top, then you could use something like this:
var valHeight = 0.5;
var result = $("#item").offset().top * valHeight;
$("#AnotherItem").height(result + "px");

You need to use .offset() as there is no method as .top() in jQuery
Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
valHeight should be a number
Code
var valHeight = 50; //Or, parseInt("50px")
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");

Related

Is there a JavaScript function to link ranges (top range 0----100 bottom range 55%----24%) known top input, want bottom value output

The following image will help explain what I am trying to achieve...
The top line (A) is a given calculated JavaScript value, lets call this the input.
The bottom line (B) is the output, so whatever input to (A) is given (will always be within the range) if a line (like the green one shown) were to be drawn I need the value of the output.
I have tried to search for phrases like "linked range", "parallel linked values" and similar but I think half of my problem is not knowing what this kind of calulation is called.
Usually I would be able to show what I have tried but on this one I really dont have a clue where to start.
Any help greatly appreciated.
So get the percentage in A
percentage = A[value] / ( A[max] - A[min] )
Use that to figure out the value in second
result = B[max] - percentage * (B[max] - B[min])
so basic JavaScript
var aMin = 0;
var aMax = 500;
var bMin = 24;
var bMax = 55;
var aValue = 100;
var percentage = aValue / ( aMax - aMin );
var result = bMax - percentage * (bMax - bMin);
console.log(result + "%");

Subtract 1 from variable jQuery

Having some trouble getting this right. I'm very new to jQuery, so trying to get better and learn.
Currently I am getting 2 different values from a html table using the following code
var sellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var buyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
These both output a value such as $13,000,000
I am then wanting to subtract 1 from these values (making it $12,999,999) before pasting them to an input as such
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
However, I am having some trouble with how to subtract $1 from these.
I tried using sellPrice--; but without success.
I've also tried adding - 1; at the end of each variable, but did not succeed either.
I tried to test something like this, but did not work either.
var minusOne = -1;
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = (getCurrentSellPrice - minusOne);
var buyPrice = (getCurrentBuyPrice - minusOne);
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);`
Trying my best to familiarize myself with jQuery :)
Any help is much appreciated!
Solved using this
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = Number(getCurrentSellPrice.replace(/[^0-9\.]+/g,"")) - 1;
var buyPrice = Number(getCurrentBuyPrice.replace(/[^0-9\.]+/g,"")) + 1;
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
Since your numbers contain currency symbol and are strings, you need to convert them to proper numbers before subtracting them. See the answer below.
How to convert a currency string to a double with jQuery or Javascript?

Javascript. How to convert 2.5/3 to say 3/2

var oneX = eval(prompt ("What's the x variable of the first set of points"));
var oneY = eval(prompt ("What's the y variable of the first set of points"));
var twoX = eval(prompt ("What's the x variable of the second set of points"));
var twoY = eval(prompt ("What's the y variable of the second set of points"));
console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);
var yRes = twoY-oneY;
var xRes = twoX-oneX;
console.log(yRes);
console.log(xRes);
var slope = xRes/yRes;
console.log("The slope is " + yRes + "/" + xRes);
This is my code. This is what the output looks like:
0.9166666666666666
0.8
2.09375
0.5714285714285714
-0.22857142857142865
1.1770833333333335
The slope is -0.22857142857142865/1.1770833333333335
However, I don't want -.22/1.177 I want -33/7 (I don't know the exact answer) I've never posted on StackOverflow before, so if I did something stupid while typing, I apologize. I'm new to programming so don't be too harsh.
The easiest way would be rounding to a certain fraction, e.g:
Math.round( slope * 10 ) + "/10"
What you're talking about is simplifying a ratio. First you multiply each number by the least common multiple to get them both into whole numbers, then divide each number by the greatest common factor to reduce them.
A full explanation of the process with examples: https://www.tutorialspoint.com/ratios_and_unit_rates/simplifying_ratio_decimals.htm

Not able to get the values needed from javascript using substring

Background
I currently have built a webApi that I used to crawl a SharePoint collection. I am getting images base64 and all the properties needed via csom. I am returning all these value via my controller to a word.js app that I am working on.
Question
The string value I am getting is "width=611px;height=262px;" . As you may be able to tell I am looking to get the width and height from this string and assign them to separate variables.
Current Approach
I have had this conversation before concerning Regex and substring and it is widely known that using substring is more efficient than regex expression. However I wonder if in this case a regex expression will be more effective than using substring?
Current Code
var Widthtest = contentObject.ImageSize[x].replace("width=", '').replace("height=", '').replace("px", '').replace(";", '').trim();
Current Code Problems
The code example supplied gets the values of both height and width combined in one string.
The code example supplied is rudimentary and may cause confusion for other developers
Desired Result
My ultimate goal is to have two variables which hold the value of the width and height separately. From a string that follows the same format as "width=611px;height=262px;"
var height = height.value;
var width = width.value;
The string is a fixed format, all you need to know is the position of the first ; - from that you can extract the values based on their offset within the string. Personally I see no reason to employ a regular expression.
var pos = str.indexOf(";");
var w = str.substr(6, pos - 8);
var h = str.substr(pos + 8, str.length - pos - 11);
One option you have is to use regex to set capturing groups for the two values separately. You can use...
var re = /width=(\d{1,4})px;height=(\d{1,4})px;/;
...as your regex. The pattern assumes that both the height and width will be between 1 and 4 digits long. The first capturing group will be the width value, and the second is the height value.
To use it practically and assign these captured values how you want, you do this:
var height = re.exec('width=611px;height=262px;')[2]; //2 for the second capturing group
var width = re.exec('width=611px;height=262px;')[1]; //1 for the first capturing group
var testStr = 'width=611px;height=262px;';
var re = /width=(\d{1,4})px;height=(\d{1,4})px;/;
console.log('Width: %d', Number(re.exec(testStr)[1]));
console.log('Height: %d', Number(re.exec(testStr)[2]));
It partly depends on the reliability of your input data. A significant advantage of a Regex is that it provides a convenient way to validate the format of the whole input string.
Not that I would necessarily recommend this approach for readability concerns, but you can do it as a one-liner using destructuring assignment in Javascript 1.7+:
[ , width, height ] = (/width=(\d+)px;height=(\d+)px;/.exec(str) || [0,0,0]).map(Number);
Note that [0,0,0] is our default fallback in case of an invalid format of the input string.
Full test code:
var str = "width=611px;height=262px;",
width, height;
[ , width, height ] = (/width=(\d+)px;height=(\d+)px;/.exec(str) || [0,0,0]).map(Number);
console.log('Width = ' + width);
console.log('Height = ' + height);
Output:
Width = 611
Height = 262
Alternate version
This one is more 'academic':
var str = "width=611px;height=262px;",
size, width, height;
if(size = /width=(\d+)px;height=(\d+)px;/.exec(str)) {
[ width, height ] = size.slice(1).map(Number);
}
else {
throw "invalid format";
}
Without Regex
If your input data is reliable enough and you don't need to check its format, something like that should work just as well:
var str = "width=611px;height=262px;",
width, height;
[ width, height ] = str.split('=').slice(1).map(function(s) { return parseInt(s, 10); });

Get css value with pixels

How can I get element width or height value which would be translated as a pixel number? All I got by using .css('width') are the expressions, not even a percentage number, like calc(-25px + 50%).
Edit
my code here. (Chrome)
var bars_width = element.css('width');
$('.histgram-content').css('width', bars_width);
bars_width = parseInt(bars_width.replace('px', '')) * 0.85;
$('.histgram-bar').css('width', (bars_width/data.length).toFixed(0).toString() + 'px');
/*** average Y ***/
var graph_height = $('.histgram-graph').css('height');
graph_height = parseInt(graph_height.replace('px', ''));
var average_height = $('.average-line').css('top');
average_height = graph_height - parseInt(average_height.replace('px', ''));
The average_height returns the expression I said. The last line got the result of 'NaN'.
You can use any of jQuery's dimension related methods:
width()
height()
outerWidth()
outerHeight()
Working example
Use window.getComputedStyle(),example:
window.getComputedStyle($('div'))['width']
You can height
$('#element-id').height();
You can width
$('#element-id').width();

Categories