Village
Village

Reputation: 24373

How to make the page load scrolled down to <div> when loaded?

I need to make sure that a specific line is visible when the user loads the page, even if that line appears many lines later in the page. In other words, when the page loads, it instantly jumps to that marked line. The line simply needs to be somewhere within the visible screen of the browser window. It is marked like this:

<div class="scrollhere">This line should always be visible when the page loads.</div>

How can I make the page load mid-way down the page, wherever a specific <div class="scrollhere"> is found?

Upvotes: 1

Views: 1583

Answers (3)

EnigmaRM
EnigmaRM

Reputation: 7632

So if you can't edit the HTML at all, then you'll need to use JavaScript or jQuery. This is a function that I've used to scroll to an element.

Javascript

This will query the DOM for all elements that have your class scrollhere. And we'll select just the first item in the array (to go to the first element). Then we'll use the scrollIntoView().

document.getElementsByClassName('scrollhere')[0].scrollIntoView()

jQuery

/*
 * A scrollTo function that gets passed a selector (ID, class, element) & an optional offset
 *
 * @param {string}  location ('#resultsTop')
 * @param {integer} offset   (-100)
 */
function scrollTo(location, offset) {
    $("html, body").animate({scrollTop: ($(location).offset().top + (offset || 0) )}, "slow");
    return false;
};

In your case, you'd call this function as follows:

scrollTo('.scrollhere');

You could also optionally pass in an offset. So maybe you don't want to scroll to the top of that element. But would rather scroll to 100 pixels above it.

scrollTo('.scrollhere',-100);

And being that you can't edit the HTML, then you'll definitely want to use a listener.

$(document).ready(function(){
  scrollTo('.scrollhere',-100);
});

Upvotes: 4

jwatts1980
jwatts1980

Reputation: 7346

This is a pure JavaScript example. No jQuery required.

Here is a simple example of this answer in JSFiddle.

window.onload = function() {
    var divs = document.getElementsByTagName("div");

    for (var i in divs) {
        if (divs[i].className.indexOf("class2") > -1) {
            //Finds top of of the element
            var top = 0;
            var obj = divs[i];

            if (obj.offsetParent) {
                do {
                    top += obj.offsetTop;
                } while (obj = obj.offsetParent);
            }

            //Scroll to location
            window.scroll(0, top);

            break;
        }
    }
};

Upvotes: 2

Ramiz Wachtler
Ramiz Wachtler

Reputation: 5683

This snippet may help you

$('html, body').animate({
    scrollTop: ($('.class').first().offset().top)
},500);

Upvotes: 1

Related Questions