Quantcast
Channel: Peter of the Norse Thinks He’s Smarter than You
Viewing all articles
Browse latest Browse all 54

Show the whole line with Javascript

$
0
0

Sometime something happens that we can’t see because the effected part is scrolled off screen. Most of the time it doesn’t happen because the button to trigger a DOM change is part of the DOM element. But sometimes something in another window or frame will change the main view. I first noticed the problem when I was testing adding a new line at the end of the playlist. The new div was added below the bottom of the window, so I couldn’t see it. The answer is to scroll the window to show the element. There are auto-scroll jQuery plugins out there, but they are designed to replace anchor links. I would make my own plugin, but my requirements are orthogonal to a typical use case.

The first step is to find the where the top and bottom of the line we want to see are.

jQuery.fn.showLine = function() {
    var line_top = this.offset().top;
    var line_bottom = line_top + this.outerHeight() + 18;

The 18px added to the bottom is for the height of the insert link. It overlaps the next line a little bit. I also add for the height of the postition: fixed header.

    var win_top = $(window).scrollTop() + 45;
    var win_bottom = win_top + $(window).height();

    if (line_top < win_top) {
        var new_top = line_top - 54;
    } else if (line_bottom > win_bottom) {
        var new_top = line_bottom - $(window).height() + 9;
    } else {
        return;
    }

If any part of the line is scrolled off the top or bottom, then we find the nearest scroll amount that will show the whole thing, plus a little bit for padding. Finally, we animate the scroll.

    $('body, html').animate({scrollTop: new_top}, 400);
};

I use $(window) to find the value, because it always works. But it doesn’t animate. So I have to use both body and html because different browsers work differently. One will respond, and the other will simply ignore scrollTop.

Watch for my next post where I rave about django-taggit.


Viewing all articles
Browse latest Browse all 54

Trending Articles