Edit in JSFiddle

$(function() {
  var $window = $(window);
  var $sidebar = $(".sidebar");
  var $sidebarTop = $sidebar.position().top;
  var $sidebarHeight = $sidebar.height();
  var $footer = $('.footer');
  var $footerTop = $footer.position().top;

  $window.scroll(function(event) {
    $sidebar.addClass("fixed");
    var $scrollTop = $window.scrollTop();
    var $topPosition = Math.max(0, $sidebarTop - $scrollTop);
    
    if ($scrollTop + $sidebarHeight > $footerTop) {
      var $topPosition = Math.min($topPosition, $footerTop - $scrollTop - $sidebarHeight);
    }

    $sidebar.css("top", $topPosition);
  });
});
<div class="header">HEADER</div>
<div class="content">CONTENT</div>
<div class="sidebar">FIXED SIDEBAR</div>
<div class="footer">FOOTER</div>
body{width:100%;margin: 10px 0;}
.header {
  width: 100%;
  background: #800005;
  height: 80px;
}
.content {
  width: 80%;
  background: #ff8f00;
  height: 800px;
  float: left;
}
.sidebar {
  width: 20%;
  background: #cc0d0d;
  height: 100px;
  float: right;
}
.sidebar.fixed {
  position: fixed;
  right: 50%;
  margin-right: -50%;
}
.footer {
  width: 100%;
  background: gray;
  height: 500px;
  clear: both;
}
*{
  color: #fff;
}