2

I have an html page with three divs containing text content. I want to scroll to a particular div depending upon the link that the user clicks on the home page.

There are three links on the home page; so what I want is if the user clicks on link 1 he is scrolled to div 1 on the resultant page, if he clicks on link 2 on the home page, then the page is scrolled to div 2 on resultant page and so on.

merv
  • 42,696
  • 7
  • 122
  • 170
user1510326
  • 31
  • 1
  • 3
  • This is basic html, not JS or CSS. Read about the `name` attribute on W3Schools: [HTML Links](http://www.w3schools.com/html/html_links.asp). As noted there, you can use the `id` attribute on all modern browsers. – merv Jul 08 '12 at 17:24
  • Welcome to SO. Kindly google before posting your queries here. – gopi1410 Jul 08 '12 at 17:26
  • 2
    If you mean **animated** scrolling: http://stackoverflow.com/questions/6677035/jquery-scroll-to-element – Kerstomaat Jul 08 '12 at 17:34
  • @merv [Why you shouldn't use w3schools.com](http://w3fools.com) - Link the official [HTML spec](http://www.w3.org/TR/html401/) instead. And for this special case the [link section](http://www.w3.org/TR/html401/struct/links.html) – Andreas Jul 08 '12 at 18:07

3 Answers3

3

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.

Use a bookmark with the anchor tag:

<a href="results.html#first-div">First</a>
<a href="results.html#second-div">Second</a>
<a href="results.html#third-div">Third</a>

You would just substitute the value after the '#' symbol to the appropriate element IDs.

Reference: http://devedge-temp.mozilla.org/library/manuals/1998/htmlguide/tags7.html

RobB
  • 8,408
  • 1
  • 23
  • 34
2

Easiest method is using Fragment Identifier. Whenever you are creating links, attach the id of the element you want to scroll to, on the end of link. For example:

link.html#divToScrollTo

An example usage:

<a href="link.html#divToScrollTo">Scroll to div with divToScrollTo as id</a>

After clicking on this link, the browser to first navigate to link.html and then scroll to an element with divToScrollTo Link.

Starx
  • 72,283
  • 42
  • 174
  • 253
2

Most if not all new browsers also support the id as an anchor destination

<div id="div1">...</div>

Will respond to <a href="page2.html#div1">...</a>

as well as the name attribute does

mplungjan
  • 134,906
  • 25
  • 152
  • 209