Q:

Move ball up and right

My previous program bounces a ball but now I want the user to be able to move it up and down, left and right whenever they want. So far my right and down buttons work but the logic for my left and up don't.
In my mind, the following code is correct but I guess it isn't
function moveU() {
    var currentTopPos = parseInt($("#ball").css('top'));
    // define the new position
    var newBottomPos = currentTopPos - velocity_y;

    if (newBottomPos >= maxTop || newBottomPos <= 0)
        velocity_y *= 0; // multiply the value by -1

    $("#ball").css('top', newBottomPos + 'px');
    maxTop = parseInt($("#outerbox").css('top')) - parseInt($("#outerbox").css('border-left-top')) - parseInt($("#ball").css('top'));
}

I currently have no errors. The ball simply doesn't move.
https://jsfiddle.net/W4Km8/4931/

A:

Here are some suggestions.

Create a single move function, which moves the ball a given x or y amount, and then calls itself using a timer:
function move(x, y) {
  //movement code   
  moveBall= setTimeout(function() {
    move(x, y);
  },20);
}

You could then have a single function that handles all the movement buttons:
$('.btn-primary').click(function() {
  $('.btn-primary').prop('disabled', false);
  $(this).prop('disabled', true);
  clearInterval(moveBall);
  switch(this.id) {
    case 'moveU': move(0, -velocity_y); break;
    case 'moveD': move(0,  velocity_y); break;
    case 'moveL': move(-velocity_x, 0); break;
    case 'moveR': move( velocity_x, 0); break;
  }
});

Instead of determining the current position of the ball and adding an offset, use jQuery's css() syntax for changing by a relative amount (+=):
$('#ball').css({
  top : '+=' + y,
  left: '+=' + x
});

If the ball is outside its container, simply reverse the relative direction (-=):
ofs= $('#ball').offset();

if(ofs.left < maxLeft || ofs.left+ballWidth  > maxRight ||
   ofs.top  < maxTop  || ofs.top +ballHeight > maxBottom
  ) {
  $('#ball').css({
    top : '-=' + y,
    left: '-=' + x
  });
}

I've put these suggestions together in this Fiddle:
http://jsfiddle.net/s1v128Lh/

