Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Jquery : Mathematically Divide Two Variables

Here's my code:

var frameWidth = 400;
var imageWidth = $('#inner-image').css('width');
var numberOfFrames = imageWidth/frameWidth;

How do I make "numberOfFrames" display as a quotient? I.E. process "frameWidth" and "imageWidth" as numbers, rather than objects?

Let me know if I need to explain myself more clearly. Thanks!

like image 254
Rrryyyaaannn Avatar asked Feb 11 '11 01:02

Rrryyyaaannn


People also ask

How to divide 2 numbers in JavaScript?

Dividing. The division operator ( / ) divides numbers.

How do you divide variables in Javascript?

The division assignment operator ( /= ) divides a variable by the value of the right operand and assigns the result to the variable.

How to divide a value in html?

HTML. Division The division operator (/) divides two or more numbers.


1 Answers

.css('width') is likely returning the value with px. You can use parseInt() to get only the number.

var frameWidth = 400;
var imageWidth = parseInt( $('#inner-image').css('width'), 10);
var numberOfFrames = imageWidth/frameWidth;

The second argument 10 specifies the base that parseInt() should use.

You can also use the width()(docs) method to get the result without the px.

var frameWidth = 400;
var imageWidth = +$('#inner-image').width();
var numberOfFrames = imageWidth/frameWidth;

Here I used the unary + operator to make it a Number instead of a String.

like image 150
user113716 Avatar answered Nov 02 '22 18:11

user113716