Amberlamps
Amberlamps

Reputation: 40448

Why does the browser jumps to ID when changing hash?

Assume I have following markup:

<div id ="About" style="height: 2000px">
    About
</div>
<div id="Work" style="height: 2000px">
    Work
</div>

When I run location.hash = 'Work'; the browser jumps right to the position of the "Work" element. I was expecting that behaviour with an anchor tag with a name attribute. But in our case it is a div container with an ID. I tested this in IE8/9 and Chrome.

Why does the browser jumps to the div container when changing the hash?

For your convenience I openend a jsFiddle.

Upvotes: 2

Views: 885

Answers (2)

yakxxx
yakxxx

Reputation: 2941

It is a feature. It is designed so and you can read about it in rfc2854. Let me quote it for you:

Fragment Identifiers

The URI specification [URI] notes that the semantics of a fragment identifier (part of a URI after a "#") is a property of the data
resulting from a retrieval action, and that the format and
interpretation of fragment identifiers is dependent on the media type of the retrieval result.

For documents labeled as text/html, the fragment identifier
designates the correspondingly named element; any element may be
named with the "id" attribute, and A, APPLET, FRAME, IFRAME, IMG and
MAP elements may be named with a "name" attribute. This is described in detail in [HTML40] section 12.

Upvotes: 1

Andy
Andy

Reputation: 14575

It's not just anchors with name attributes, anything with an ID can be jumped to using location.hash or just #Work in the url.

For example, clicking here will take you to the id #show-editor-button in this page

Upvotes: 2

Related Questions