Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery divide a variable

Why won't this work? Tearing my hear out...

This fiddle has been updated with the approved answer http://jsfiddle.net/jbreezy/pswdn2wb/

$(document).ready(function() { var marginFix = $('.marginFix').css('font-size'); var onethirdMargin = parseInt(marginFix / 3); $('.marginFix').css({"margin-top":marginFix}); $('.marginFix').css({"margin-bottom":onethirdMargin}); });

As you can see there, I just want the variable 'onethirdMargin' to be 1/3 of the other variable.

So essentially no matter what you ever set the font-size to in the css, that elements margin-top will equal to said font-size, and the margin-bottom will be 1/3 of that automatically (If you apply the class marginFix to it). Currently the margin-bottom is still just staying equal as well... Any help is super appreciated!

like image 564
Jbreen37 Avatar asked Dec 29 '14 23:12

Jbreen37


1 Answers

change

var onethirdMargin = parseInt(marginFix / 3);

to

var onethirdMargin = parseInt(marginFix, 10) / 3;

If you parseint on "24px" it makes it the integer 24, then you can divide by 3.

According to Mozilla, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt you should always specify the 2nd parameter to ParseInt, the 10, it's the base you want to parse into. Thanks to Rocket Hazmat for the clarification on that.

like image 147
aaron-coding Avatar answered Sep 27 '22 23:09

aaron-coding