I'm using a simple toggle function to reveal divs when clicking on the associated heading.
What I'm aiming to achieve
1. When the heading is clicked, the hidden div will be revealed and the page scrolled so that the heading is at the top of the viewport.
2. If the page has insufficient height for the heading to move to the top, the page height will be increased to allow this to occur.
3. When the heading is clicked again, the div will be hidden but the heading remain in its current position at the top of the viewport. If a div is being toggled closed when not at the top, the page having been scrolled, then it should remain in its current position.
Other things to consider
Preventing the amount of any generated empty space at the page bottom from being sufficient to fill the entire viewport.
Current state of play
The code below will move the heading and revealed div to the top of the viewport if the page height is sufficient. When the div is hidden again, the heading drops down to its original location on the page, which is disorienting for the user.
Markup
- <h2 class="trigger">Switch<h2>
- <div>Content to toggle</div>
jQuery
- $(document).ready(function() {
- $('.trigger').next('div').hide();
- $('.trigger').click(function() {
- $('html,body').animate({scrollTop: $(this).offset().top}, 500);
- $(this).next('div').toggle();
- });
- });