0

Could someone please explain to me the supposed purpose of .Slice in this piece of code? How can you select a subset of padding-bottom? Thanks a lot.

$(this).bind('click', function(){
      var tid = $(this).attr('id');
      tid = tid.replace('play-button-', '');
      playheight = parseInt($('#play-view-' + tid, 10).height());
      playpadding = parseInt($('#play-view-' + tid, 10).css('padding-bottom').slice(0, -2));
      var flex_height = playheight + playpadding;
      setTimeout(function(){
        $('.flex-viewport').animate({height: flex_height});
      },200);
    });

--- Alternative without using slice ----

    $(this).bind('click', function(){
      var tid = $(this).attr('id');
      tid = tid.replace('playlist-button-', '');
      playheight = $('#playlist-display-' + tid).height();
      playheight = parseInt(playheight, 10);
      playpadding = ('#playlist-display-' + tid);
      playpadding = $(playpadding).css('padding-bottom');
      if (playpadding != null) {
        playpadding = parseInt(playpadding, 10);
        flex_height = playheight + playpadding;
      } else {
        flex_height = playheight;
      }
        setTimeout(function(){
        $('.flex-viewport').animate({height: flex_height});
      },200);
    });
maskedjellybean
  • 689
  • 2
  • 9
  • 16

1 Answers1

1

Slice on a string takes a substring and returns it.

In this case it gets the padding value and removes the last two characters (the units - for example px or em) so the ParseInt can parse the string as an integer.

'10px'.slice(0,-2) will return '10'

You can check this answer for some differences from the substring function:

Community
  • 1
  • 1
becquerel
  • 1,131
  • 7
  • 11
  • Ah okay. That makes sense. Except that doesn't parseInt itself remove everything that's not an integer? This code doesn't actually work and I thought it had to do with slice. So I edited my question to include a work around that does work. Is there any advantage to using slice over this? – maskedjellybean Oct 10 '13 at 15:16
  • 1
    Yeah parseInt does that. It will parse any numbers before a non-numeric character, so it should be fine without it. I can't say why slice was used in this case, maybe it was included as a precaution in case some client browser had not implemented parseInt in the same way. – becquerel Oct 10 '13 at 16:04