Dynamic sidebar height and responsive themes

1 Comment

In another post, I listed the javascript to be used in a WordPress text widget to ensure that a sidebar had the same height as a page’s content. This is a nice feature if the sidebar has a background color. When the theme is responsive, the sidebar drops to the bottom, below the main content, so it should be sized to fit its own content, not that of the main content area. All it takes is a bit of javascript that checks the current page width.

Note: This snippet uses element names based on the TwentyTwelve theme layout. If you’re using different theme, you may need to pick different elements.

<!-- this must be the last widget. It dynamically sizes the sidebar -->
<script type="text/javascript">
<!--
var divh = document.getElementById('primary').clientHeight;
var sb1 = document.getElementById('secondary').clientHeight;
document.write(" ");
if ((sb1 < divh) && (document.getElementById('page').clientWidth > 600)) {
document.getElementById('secondary').style.height=divh+"px";
}
//-->
</script>