Javascript – How to add vertical scroll bar to one div only without specifying height

csshtmljavascriptjquery

Can I add a scroll bar to a div when needed but without specifying any height either for the div itself or for a container that this div must be in?

The div is the very botton element on the page and I want user to be able to resize the browser window. So the scroll bar would appear when the "data" that dynamically add to the div reaches the botton of the page.

My page got contains only one table and second row of the table is below code.

<table border="0">
 <tr>
    <td><button type="button" onclick="$('#info').text('')" > clear info area </button></td>
 </tr>
 <tr class="tr_info">
    <td><div id='info'></div></td>  
 </tr>
</table>

I tried overflow-y: scroll; to the div but it added scroll bar to the whole window not the div.

Best Answer

Fiddle http://jsfiddle.net/RSh9H/2/show/

Corrected Fiddle : http://jsfiddle.net/RSh9H/8/show/

jQuery:

$(window).on('load resize',function(){
var heightOfWindow = $(window).height();
var totalHeightOfContents = $(document).height();
    if(heightOfWindow <= totalHeightOfContents){
        var heightExcludingInfo = $('table#main').height() - $('#info').height();
        var availableHeightForInfo = heightOfWindow - heightExcludingInfo;
        $('#info').height(availableHeightForInfo);
    }
    else{
        $('#info').css({height:'auto'});
    }
});