Anthony_Z
Anthony_Z

Reputation: 725

Recalculate the height of a container div based on height of content within tabs

I have a page that has a sticky image sidebar on the left and tabbed content on the right of differing heights. The problem I run into is that the sticky sidebar is overflowing it's container when a shorter tab has been selected.

This behavior can be observed by clicking tab 2 and scrolling down the page. The image on the left should not overflow into the footer. Tab 1 shows the correct behavior.

Here is a code example: http://codepen.io/anon/pen/gayMjx

  <section class="js-pin-container">
<div class="row">
  <div class="left-col">
    <div class="js-pin-content">
      <img src="http://placehold.it/250x250">
    </div>
  </div>
  <div class="right-col">
    <div id="tabs">
      <ul>
        <li><a href="#tabs-1">tab 1</a></li>
        <li><a href="#tabs-2">tab 2</a></li>
        <li><a href="#tabs-3">tab 3</a></li>
      </ul>
      <div id="tabs-1">
        <p style="background: silver; height: 900px;">This dive is 900px tall.</p>
      </div>
      <div id="tabs-2">
        <p style="background: silver; height: 600px;">This dive is 600px tall.</p>
      </div>
      <div id="tabs-3">
        <p style="background: silver; height: 1200px;">This dive is 1200px tall.</p>
      </div>
    </div>
  </div>
</div>

Upvotes: 9

Views: 2373

Answers (2)

Shlomi Hassid
Shlomi Hassid

Reputation: 6606

Following @piyin answer I suggest not raising the window.resize() event each time.

The reason is that in the real world you may have several functions attached to this event and you want to avoid invoking all of them on each tab switch.

The better way of recalculating the height will be to expose the plugin method recalculateLimits and attaching it to the activate event:

Working example: JSnippet Demo

Exposing the method:

     ...
        $window.resize(function () { recalculateLimits(); });
        recalculateLimits();
        //This line expose the method
        this.recalculateLimits = recalculateLimits;
        $window.load(update);

        return this;
    };
})(jQuery);

And then you can attach only it:

$(function() {

    //Attach pin:
    var pinSide = $(".js-pin-content").pin({
        containerSelector: ".js-pin-container"
    });
    //Create tabs:
    $( "#tabs" ).tabs({
        activate:function(){
            pinSide.recalculateLimits();
        }
    });

});

Upvotes: 1

Piyin
Piyin

Reputation: 1834

The problem is pin only updates its limits (recalculateLimits) when the window is resized, not when the contents of the container change. You could use a workaround so each time you open a new tab the window resize events are triggered. In other words, you could change your initialization of tabs plugin from:

$( "#tabs" ).tabs();

To:

$( "#tabs" ).tabs({
  activate:function(){
    $(window).resize();
  }
});

Here you go: http://codepen.io/anon/pen/OyYyag

Upvotes: 8

Related Questions