Javascript - transform `elem.style.left` into integer? - javascript

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.

Related

Retrieving the first value from a number pair in parenthesis

I'm using jQuery to get the CSS transform property:
this.$slider.css('transform')
The following returns:
translate(100px, 0px)
How would I get just the number 100 as a variable using javascript or jQuery?
With javascript string functions:
str = this.$slider.css('transform');
a = str.substring(str.indexOf('(')+1,str.indexOf('px'));
alert(a); //100
you can use regex:
'translate(100px, 0px)'.match(/[^\(]+\(([0-9]+)/)[1]
var transform = this.$slider.css('transform'),
first = transform.split('(')[1].split('px')[0];
a small regex would suffice to just pull the first number, but note this isn't picky that they are pixel units or anything else that might come back in the CSS
this.$slider.css('transform').match(/\d+/)
s = "translate(100px,0px)"
parseInt(s.substring(s.indexOf("(")+1), 10) // returns 100
Just take a slice starting at index 10, and send it through parseInt.
var str = this.$slider.css('transform');
var n = parseInt( str.slice(10), 10 );
Or if there will be other types of results than transform, you can do this:
var n = parseInt( str.split("(")[1], 10);

Simple math in jquery

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;

Problem with concat string in jquery animate

count = 0;
total = 2;
jQuery("#slide").everyTime(5000,function(i){
if(count == total-1) {
count = 0;
jQuery(this).stop().animate({backgroundPosition: "0px 0"}, {duration:1000});
}
else{
jQuery(this).stop().animate({backgroundPosition: "-"+950*count+"px 0"}, {duration:1000});
count++;
}
});
Hi all, i am trying to work on this. there are some problem with the "950*count". When ever i put an operator into this, it wont' work, but if i remove the *count, it work just fine.
Can someone point out what the problem is?
Thank you
Put parentheses around the calculation:
"-" + (950 * count) + "px 0"
Otherwise the expression is evaluated from left to right, first concatenating "-" with "950", then trying to multiply that.
Because there's no such number as -0.
Did you try changing "-"+950*count to "-"+parseInt(950*count) ?

Padding or margin value in pixels as integer using jQuery

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.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

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);

Categories