JSFiddle - React, Tailwind, and code Playground
HTML
<div class="header">This is the big boy header</div>
<div class="content">This is the content</div>
<div class="sidebar">
<br />
<br />
<input type='button' value='Add Button' id='addButton' />
<br />
<br />
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type='text' id='textbox1' name='textbox1' />
</div>
</div>
</div>
<div class="footer">The poor footer lies here</div>
CSS
.header {
width:100%;
background:red;
height:120px
}
.content {
width:80%;
background:blue;
height:1200px;
float:left
}
.sidebar {
width:20%;
background:yellow;
min-height:300px;
float:right;
}
.footer {
width:100%;
background:gray;
height:160px;
clear:both
}
.sidebar.fixed {
position:fixed;
right:50%;
margin-right:-50%
}
JavaScript
var $window = $(window);
var $sidebar = $(".sidebar");
var sidebarTop = $sidebar.position().top;
//var sidebarHeight = $sidebar.height(),
var $footer = $(".footer");
var footerTop = $footer.position().top;
$sidebar.addClass('fixed');
$window.scroll(function (event) {
var scrollTop = $window.scrollTop();
var topPosition = Math.max(0, sidebarTop - scrollTop);
// Ensure you are using the current sidebar height and not the initial height
topPosition = Math.min(topPosition, (footerTop - scrollTop) - $sidebar.height());
$sidebar.css('top', topPosition);
});
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
$('<div/>', {
'id': 'TextBoxDiv' + counter
}).html(
$('<label/>').html('Textbox #' + counter + ' : '))
.append($('<input type="text">').attr({
'id': 'textbox' + counter,
'name': 'textbox' + counter
})).appendTo('#TextBoxesGroup');
// Trigger the scroll handler to ensure the sidebar is properly positioned
$window.triggerHandler('scroll');
counter++;
});
});