Jquery divide cast as int issue - javascript

I am trying to divide two variables in Jquery as follows:
var image_width = parseInt($object.width());
var image_height = parseInt($object.height());
var image_ratio = image_width/image_height;
However, when I attempt to use image_ratio in an if statement...
if (image_ratio < 1) //image is taller than it is wide
{
//do something...
}
And I know that the image is taller than it is wide but the function is not entering the if statement. Is this because when two int's divide it generates an int? If so, how can I get decimal values in order to check if the ratio is less than 1?
Thanks!

what is the result of alert($object.height())? If it's possible that $object is an empty jquery collection, then.height() will return null, and parseInt(null) will return NaN, giving you NaN for image_ratio. Any comparison between NaN and another value will always return false, which would explain the behavior you're seeing.
if $object.height() is returning 0, you'll also get NaN for image_ratio, and then you need to look at your jQuery selection. Are you selecting the correct element? What does $object[0].height give you?

JavaScript doesn't have ints, only "Numbers" (double-precision floating point), so that's not the problem.
Check the actual values of each variable.

You have something else wrong because dividing two numbers will return a decimal value if they don't divide perfectly evenly. Here's a jsFiddle to see for yourself: http://jsfiddle.net/jfriend00/wnh9Q/.
var width = 4;
var height = 3;
var aspectRatio = height/width;
if (aspectRatio < 1) {
$("#if").html("Inside the if() statement."); // it goes in here
}
$("#result").html(aspectRatio); // outputs 0.75
To solve your issue, you need to look at the input values $object.width() and $object.height() and see what is wrong there.

At which point are you calling the width() and height() functions on the image object? If the image isn't yet loaded when the values are retreived, the values are probably wrong. In this case, try calculating the ratio in a function attached to the load event on the image.

No, the division doesn't give an integer result. The parseInt method doesn't give an integer result either, because there is no integer data type in Javascript.
Besides, the width and height methods returns numbers, not strings, so there is no point to parse them. That would only convert the number into a string, and then back to a number. Just get the values:
var image_width = $object.width();
var image_height = $object.height();
There is however nothing in your code that would not work, so there has to be something outside the code that you show that doesn't work.
Some possible reasons:
$object doesn't contain any elements.
The image is not loaded yet, so the element doesn't have any size.
If it's the latter, you should run your code in the load event rather than in the ready event.

Related

Random Array Picker - Javascript

i was coding for a small project but my random array picker doesnt work
var btnarray = [xfn.left, xn.left, xnln.left, xln.left, xnn.left];
(this is the array)
var rand = btnarray[Math.floor(Math.random() * 4)];
(this is the random picker var)
Well, when i start, the rand value results equal to btnarray[0]
anyone can help me please?
Oh i perfectly know that the variables are all different.
Thanks
Since your array's length is 5, you need to multiply the value of the random function by that number. Better yet, use the length property.
var rand = btnarray[Math.floor(Math.random() * btnarray.length)];
You shouldn't use Math.floor since it will make very hard to get the last element in your btnarray array, you'll need to get exactly the number btnarray.length in order to get at that element. Also, floor tends to flatten probability outcomes and looks like you're stuck on some value(s) since it's threshold is forcing you to have the greatest integer smaller than or equal to some number.
You should use round instead, this will even the probability for every array element and will give you more apparently random indexes. Try this, it's already tested with a dummy btnarray array variable and works fine.
var rand = btnarray[Math.round(Math.random() * btnarray.length)];
if you toss this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
you can just do this:
var randomValue = rando(btnarray).value
I usually go with randojs.com because it can handle pretty much any random functionality you need, and it's all short and easy to read.

I am trying to convert numbers into their opposite value regardless of whether number is positive or negative

I tried this code, it works
const opposite = number => -number
Code won't run, just trying to experiment with different ideas
function opposite(number){
return Math.abs(number)
}
opposite(1)
What Am I missing here ?
Your code is running, your just noticing the output for two reasons:
returning a value from your function doesn't mean it will be logged to the console. You need to console.log() the function call to see its output (the returned value)
Math.abs() will get the absolute value of a number passed into it (which isn't the same as the opposite). You can think of this as the distance a given number is away from 0. Thus doing Math.abs(1) will give 1 not -1, perhaps making you think your function isn't working. With this in mind Math.abs() will only give you the opposite for numbers which are negative, not positive.
See running example below:
function opposite(number){
return Math.abs(number)
}
console.log(opposite(-1)); // returns 1
console.log(opposite(1)); // returns 1

Displaying Math.random() in h1 tag jQuery

All I'm trying to do is display the math.random number in the h1 tag by using jQuery and for some reason it's not working I'm not sure whats going wrong. For some reason when I take out the function it works but why is that?
HTML
<h1></h1>
jQuery
function time(){
var number = Math.floor(Math.random());
$('h1').text(number);
}
You are using $ which is a jquery selector in a form that doesnot know about JQuery .
So please use this code instead :
function Thetime(){
$(document).ready(function() {
var number = Math.floor(Math.random());
$('h1').text(number);
});
}
Hope this will solve your problem .
a side note : you are flooring the generated number , that might always lead to ZERO , So you can also only use Math.random() instead of Math.floor(Math.random());
Thanks
You need to actually call the time() function to make it perform its operations.
Here is your code running:
function time(){
var number = Math.floor(Math.random());
$('h1').text(number);
}
// call your function to run it
time();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
NOTE: You may notice that your number is always 0. This is because Math.random() creates a float between 0 and 1 (eg: 0.22378). Likewise, Math.floor() will take any floating point number and round it down to the nearest integer. So a random number like 0.22378 will always be floored to 0. If you want to randomize between a range of whole numbers you need to multiply your random number by your maximum then floor the result.
var max = 30;
var number = Math.floor(Math.random() * max);
#ScottMarcus answered the question, all I had to do was add a document.ready to the function. Just going to leave this up for any new beginning coders.

Round every textbox to 2 decimal places

This is probably really simple, but for the life of me I can't work out how to do it. So here goes: I have a large form with lots of text boxes, which are all currency based and so need to be rounded off to 2 decimal places. The values of these textboxes are all generated dynamically by some JavaScript functions I wrote, and I can use .toFixed(2); to round them up/down to 2 decimal places. However, it gets tiring and repetitive to have to put this after working out each value of each textbox. How could I write a simple piece of JavaScript (can be jQuery) to target all the textboxes and round them ALL to 2 decimal places?
Thanks for any help :)
P.S Sorry for the lack of any code, but there isn't really any to show, as its all locked up in big functions. But here's what I'm essentially doing:
function workOutSomeVal() {
// lots of code to work out values and stuff
var finalValue = some mathematical equation to work out value;
var anotherValue = a different value;
$(".some-textbox").val((finalValue).toFixed(2));
$(".another-textbox").val((anotherValue).toFixed(2));
} // my question is, how could I get rid of .toFixed(2) and put in a generic statement somewhere to target all the textboxes?
You can have a function you call that does this:
function roundTextBoxes() {
$("input[type=text]").val(function() {
return (+this.value).toFixed(2);
});
}
...and then call that any time any of them changes. Live Example: http://jsbin.com/toyoc/1
It will probably mean that sometimes, a user looking at the page who does the mental arithmetic will find that it doesn't quite add up...
You can give a common class to all the textboxes which you want to be "roundable", and then select then using that class and apply your rounding logic to each of them.
// let's say all the roundable textboxes have the class "roundable"
$('.roundable').each(function() {
var value = // some mathematical equation to work out value
$(this).val((value).toFixed(2));
});
Another appoach:
Why don't you put value.toFixed(2) at the end of your calculation ?
var finalValue = function(){
// var value = some calculation
return value.toFixed();
}
Or - if you need the full value elsewhere, create a new function:
var finalValueView = function(){
finalValue().toFixed(2);
}
function workOutSomeVal() {
// ...
$(".some-textbox").val(finalValueView);
}
Use Math.round(num * 100) / 100

attribute maxlength of input field is changing, but input doesn't care

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.
I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?
my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters(); //this gets called often
EDIT: http://jsfiddle.net/mDw6f/
EDITTTT:
You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)
Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.
Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.
Cheers
Real Fiddle Example
Try using this fiddle:
Working Demo
Use the html input like I did in the code, no need to specify the maxlength attribute to it.
<input type="text" class="my_input_class"/>
and the script
my_var = 25; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters();

Categories

Resources