H. Ferrence
H. Ferrence

Reputation: 8116

jQuery Auto Scroll to DIV ID

I have a div id a third of the way down a web page

HTML

<div id="scrollHere"></div>

JavaScript

    <script>
$(document).ready(function(){

var elem = $('#scrollHere');
if(elem) {
    $(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);
}

/*
var destination = $('#scrollHere').offset().top;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-75}, 800 );
    return false;
*/
/*
var elem = $('#scrollHere');
if(elem) {

$(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);
    //$('html').scrollTop(elem.offset().top);
    //$('html').scrollLeft(elem.offset().left);
}
*/


/*
    var elem = $('#scrollHere');
    if(elem) {
        //$.scrollTo(elem.left, elem.top);
        //$(document).stop().scrollTo( elem.offset().left, elem.offset().top );
    }
*/

}); // end .ready()
    </script>

CSS

#scrollHere{
    position:relative;
    top:500px;
    left:1000px;
    border:1px solid black;
    width:50px;
    height:50px;
}

But I can't get autoscroll to take me to the div id on page refresh.

Am I using the wrong JavaScript commands?

Upvotes: 1

Views: 13986

Answers (2)

Starx
Starx

Reputation: 79069

The most efficient way to achieving this by changing the scrollTop and scrollLeft of the DOM window.

$(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);

Demo

Upvotes: 1

Alex
Alex

Reputation: 6406

Is there a scrollTo-Function in jQuery? I thought you need a plugin for that. However, this works for me:

http://jsfiddle.net/5VQCD/

var elem = $('#scrollHere');
if(elem) {
    $('html').scrollTop(elem.offset().top);
    $('html').scrollLeft(elem.offset().left);
}

Upvotes: 2

Related Questions