1

I have two buttons to move a box up or down with JQuery being used to get the CSS 'top' value which is being either added to or subtracted from. When subtracted from, it works as expected but when added to it does not.

It seems to be a case of the addition sign being confused for concatenation instead. Some brackets were then put around the numbers being added but this made no difference.

The working code, ie, when subtraction occurs is shown below:

$('#dir_panel_form').css({
    'top': $('#dir_panel_form').css('top').substring(0, $('#dir_panel_form').css('top').length - 2) - 30 + 'px'
}); 

The non-working code, ie, when addition occurs is shown below with the extra set of brackets bolded:

$('#dir_panel_form').css({
    'top': ($('#dir_panel_form').css('top').substring(0, $('#dir_panel_form').css('top').length - 2) + 30) + 'px'
}); 

The snippet with the extra brackets (again bolded) is also shown below:

($('#dir_panel_form').css('top').substring(0, $('#dir_panel_form').css('top').length - 2) + 30)

Can anyone sought this out?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
havelly
  • 109
  • 1
  • 11
  • Possible duplicate of [How to force JS to do math instead of putting two strings together](http://stackoverflow.com/questions/4841373/how-to-force-js-to-do-math-instead-of-putting-two-strings-together) – JJJ Dec 16 '15 at 08:02

2 Answers2

2

The issue is because substring returns a string. Therefore the following + operator becomes a concatenation instead of an addition. You need to use parseInt() to convert the string to an integer.

$('#dir_panel_form').css({
    'top': parseInt($('#dir_panel_form').css('top').substring(0, $('#dir_panel_form').css('top').length - 2), 10) + 30 + 'px'
}); 

Also note that you can improve this further by using the shorter slice(0, -2) to remove the last two characters from the string and providing the css() method with a function. This will improve performance as there will only be a single request to the DOM instead of three.

$('#dir_panel_form').css('top', function(i, top) {
    return parseInt(top.substring(0, -2), 10) + 30 + 'px'
}); 
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Try to use parseInt instead of substring function, so replace

($('#dir_panel_form').css('top').substring(0, $('#dir_panel_form').css('top').length - 2) + 30) + 'px'

to

parseInt($('#dir_panel_form').css('top')) + 30 + 'px'
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • Thank you for that - it works. You have probably guessed the substring() was used to get rid of the 'px' but the parseInt() appears to do that instead - great simplification. – havelly Dec 16 '15 at 08:20