jQuery has height() en width() functions that returns the height or width in pixels as integer...
How can I get a padding or margin value of an element in pixels and as integer using jQuery?
My first idea was to do the following:
var padding = parseInt(jQuery("myId").css("padding-top"));
But if padding is given in ems for example, how can I get the value in pixels?
Looking into the JSizes plugin suggested by Chris Pebble i realized that my own version was the right one :). jQuery returns always value in pixels, so just parsing it to integer was the solution.
Thanks to Chris Pebble and Ian Robinson
You should be able to use CSS (http://docs.jquery.com/CSS/css#name). You may have to be more specific such as "padding-left" or "margin-top".
Example:
CSS
a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}
JS
$("a").css("margin-top");
The result is 10px.
If you want to get the integer value, you can do the following:
parseInt($("a").css("margin-top"))
Compare outer and inner height/widths to get the total margin and padding:
var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());
The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10); returns the left margin as an Integer.
This is what JSizes use.
PLEASE don't go loading another library just to do something that's already natively available!
jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:
http://jsfiddle.net/BXnXJ/
$(document).ready(function () {
var $h1 = $('h1');
console.log($h1);
$h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
$h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});
Here's how you can get the surrounding dimentions:
var elem = $('#myId');
var marginTopBottom = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight = elem.outerWidth(true) - elem.outerWidth();
var borderTopBottom = elem.outerHeight() - elem.innerHeight();
var borderLeftRight = elem.outerWidth() - elem.innerWidth();
var paddingTopBottom = elem.innerHeight() - elem.height();
var paddingLeftRight = elem.innerWidth() - elem.width();
Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)
You can just grab them as with any CSS attribute:
alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));
You can set them with a second attribute in the css method:
$("#mybox").css("padding-right", "20px");
EDIT: If you need just the pixel value, use parseInt(val, 10):
parseInt($("#mybox").css("padding-right", "20px"), 10);
This simple function will do it:
$.fn.pixels = function(property) {
return parseInt(this.css(property).slice(0,-2));
};
Usage:
var padding = $('#myId').pixels('paddingTop');
Parse int
parseInt(canvas.css("margin-left"));
returns 0 for 0px
ok just to answer the original question:
you can get the padding as a usable integer like this:
var padding =
parseInt($("myId").css("padding-top").replace("ems",""));
If you have defined another measurement like px just replace "ems" with "px".
parseInt interprets the stringpart as a wrong value so its important to replace it with ... nothing.
You could also extend the jquery framework yourself with something like:
jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();
return {
top: marginTop,
left: marginLeft
}};
Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.
fx.
$("#myObject").margin().top
Don't use string.replace("px", ""));
Use parseInt or parseFloat!
I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...
Shamelessly adopted from Quickredfox.
jQuersy.fn.cssNum = function(){
return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};
update
Changed to parseInt(val, 10) since it is faster than parseFloat.
http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/20
Not to necro but I made this which can determine pixels based on a variety of values:
$.fn.extend({
pixels: function (property, base) {
var value = $(this).css(property);
var original = value;
var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1
? $(this).parent().outerWidth()
: $(this).parent().outerHeight();
// EM Conversion Factor
base = base || 16;
if (value == 'auto' || value == 'inherit')
return outer || 0;
value = value.replace('rem', '');
value = value.replace('em', '');
if (value !== original) {
value = parseFloat(value);
return value ? base * value : 0;
}
value = value.replace('pt', '');
if (value !== original) {
value = parseFloat(value);
return value ? value * 1.333333 : 0; // 1pt = 1.333px
}
value = value.replace('%', '');
if (value !== original) {
value = parseFloat(value);
return value ? (outer * value / 100) : 0;
}
value = value.replace('px', '');
return parseFloat(value) || 0;
}
});
This way, we take into account for sizing, and auto / inherit.
Related
I have the following:
var offset;
offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level) || 0;
offset += 100;
When I use the debugger this offset now has 0100. I want it to add like a number not a string. How can I do this?
Please note I changed the question slightly because I realized I was getting the value from local storage. I assume this returns a string. But I am still not sure how to solve this.
The code you gave won't do that. I assume your value in your actual code is a numeric string. If so, the + will behave as a string concatenation operator, so you must convert the value to a number before using +.
You can do that with parseFloat().
var offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level);
offset = parseFloat(offset) || 0;
Or in most cases, you can simply use the unary version of + to do the conversion.
offset = +offset || 0;
When I click "+ 1", then in the "0" appears "NaN". Why ?
HTML:
<table>
<tr><td id="run">0</td></tr>
</table>
+ 1
JS:
function plus(){
document.getElementById("run").innerHTML = ( document.getElementById("run").value + 1 );
}
It happens because value property can be applied only to input or select elements.
Pay attention that you need to convert your string value to numeric, otherwise you will get string concatenation. It can be done with parseInt or parseFloat functions.
var val = parseInt(document.getElementById("run").innerHTML, 10);
document.getElementById("run").innerHTML = ( val + 1 );
That's because:
document.getElementById("run").value
will be undefined and undefined + 1 == NaN.
Input boxes have a value property, but nodes like <td /> have .innerHTML() or .innerText().
Also, note that '0' + 1 == '01', so you have to do some casting as well:
parseInt(document.getElementById('run').innerHTML, 10) + 1;
The additional radix - 10 - is necessary to convert strings that may be interpreted as octal numbers :)
Try this
function plus(){
document.getElementById("run").innerHTML = parseInt( document.getElementById("run").value) + 1;
}
Because attribute values are always strings and string + 1 is a NaN in JavaScript.
To solve this, use string.toFloat():
function plus(){
document.getElementById("run").innerHTML = ( document.getElementById("run").value.toFloat() + 1 );
}
Or use parseInt():
function plus(){
document.getElementById("run").innerHTML = ( parseInt(document.getElementById("run").value) + 1 );
}
Or use the ~~() function as a trick, but this will result in a not readable source.
I guess this question still deserve a better answer, but I may be wrong. )
Let's check what happens in your plus function. First, you get an element by its id, with
var targetElement = document.getElementById('run');
It's actually a reference to the object of DOMElement type. Which is quite easy to see by checking its nodeType property.
if (targetElement.nodeType === 1) { alert("It's an element!"); }
DOM Elements have plenty of nice properties, but their nodeValue is always equal to null. So if you want to work with its text content, you can either look for the child textNodes - or just use innerHTML property. It's a string, yes, but Javascript will manage to convert it to a normal number if it's numeric (and 0 is numeric, from what I remember :).
So your plus function can be actually written just like this (the proof):
document.getElementById('run').innerHTML++;
Because value is a property of HTMLInputElement and the TD element is not an HTMLInputElement but a HTMLTableCellElement, so doesn't have that property and:
undefined + 1; // NaN - Not a Number
You can basically use the same innerHTML property you used to set the content also to get it:
function plus() {
// no need to execute `getElementById` twice
var td = document.getElementById("run");
td.innerHTML = +td.innerHTML + 1;
}
To convert the value in Number I used the unary plus operator. You could also check if it's NaN before use it, something like:
function plus() {
var td = document.getElementById("run");
var value = +td.innerHTML || 0;
td.innerHTML = value + 1;
}
In that case if it's NaN (or 0, but in that case it's an identity) will set to 0, and the count will start from 1 without give any error.
Additionally, I would say that it could be better use the textContent property where supported, but then the code will be a bit more complex to handle all browser's (e.g. in some IE versions you need to use innerText instead), and innerHTMLcould be good in most of the cases.
I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;
I need to make this comparison:
if (x < siteA.style.left || x > siteA.style.left + land.width() ) {
however siteA.style.left returns 20px (e.g) so the condition doesn't work. How do I remove the px and transform it into an integer so I can work with it?
I tried alert(parseInt(siteA.style.left)) and it returned NaN however alert(siteA.style.left) returned 30px, 60px etc.
Use parseInt:
var leftPos = parseInt(siteA.style.left, 10);
where 10 is the base, good practice to always specify it.
Just use parseInt().
Have you tried this?
var left = parseInt(siteA.style.left.replace('px', ''), 10)
When using jQuery you can use $('#siteA').offset().left which returns only the integer value.
I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);