Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to scroll to certain anchor/div on page load?

Lately im trying to use jquery more often and right now im having some problem i'd like to solve with jquery hope u could help me.

I have some web page that includes some anchor tag (lets say the anchor is located in the middle of the page) and on the event onload i want the page to start on that certain anchor tag location meaning the page will be "scrolled" automaticaly to a certain location.

That was my previous solution (which is quite ugly since it adds #i to my url)

window.onload = window.location.hash = 'i'; 

Anyway could u tell me how can i do it with jquery?

notice: i don't want the user to feel any slide or effect while getting to this location

like image 361
Popokoko Avatar asked Mar 18 '12 10:03

Popokoko


People also ask

How do I scroll to a certain div on page load?

Just get the div id from query string and on page load pass it to above code like: $('#' + divToScrollTo). offset(). top , where divToScrollTo is js variable where we have stored the query string value.

How do I scroll to a specific div in HTML?

If you want to scroll the current document to a particular place, the value of HREF should be the name of the anchor to which to scroll, preceded by the # sign. If you want to open another document at an anchor, give the URL for the document, followed by #, followed by the name of the anchor.

How do I smooth scroll to anchor?

To achieve a smooth scrolling effect for anchor links, add a scroll modifier—block T178 from the "Other" category to the bottom of your page. Now, when you click an anchor link, the transition will be smoothly animated.

How do I scroll down to a specific element in JavaScript?

Use the scroll() Function to Scroll to an Element in JavaScript. The element interface's scroll() function scrolls to a specific set of coordinates within a given element. This is suitable for Chrome and Firefox and not for the rest. window.


1 Answers

Use the following simple example

function scrollToElement(ele) {     $(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left); } 

where ele is your element (jQuery) .. for example : scrollToElement($('#myid'));

like image 180
Manse Avatar answered Sep 26 '22 01:09

Manse