Reputation: 3
I made a function to move an element base on there left CSS value. My function work in one direction but I realize a strange problem in the other direction.
First I extract the left value of a element :
$left_position = element.css('left').replace(/[^-\d\.]/g, ''); // left_position = -400
now when I add a positive value to that, for the new position :
$new_left_position = $left_position + 400;
The result I was expected was 0 but instead the result is : -400400
If I replace the "+" sign by a "-" sign it work the result is -800
Any idea why? Thanks
Upvotes: 0
Views: 217
Reputation: 141
Using ParseInt('$variableName')
you can achieve your desired result.
I hope following will also helpful in your work. Using simple jQuery code you can move things easily as follows:
HTML:
<input type="button" value="To Left" onclick="moveStuff('-=100px')" />
<input type="button" value="To Right" onclick="moveStuff('+=100px')" />
<div id="stuff" style="padding:10px;background-color:#ff00f0;width:120px">I AM MOVING</div>
jQuery Function:
function moveStuff(px) {
$('#stuff').animate({
'marginLeft' : px
},1000);
}
WORKING SOLUTION on JS Bin
Upvotes: 0
Reputation: 12391
In javascript the +
sign is for string concatantion on strings.
var string = "400";
console.log(string + 400); //400400
console.log(parseInt(string) + 400); //800
Upvotes: 0
Reputation: 2783
Parse it to integer, you are concatinating it because one element ($left_position) is a string.
$new_left_position = parseInt($left_position) + 400;
function ".replace()" will ofcourse always return a string so your variable is a string aswell.
Upvotes: 3