0

I want browse directly to my site div by this way:

www.xyz.com/#divname

some sites I saw , I know there is a way to do it ,can anyone tell me the code

I have tried

window.location.href=#divname

but not scrolling.

1
  • 1
    Your div should have an id that matches. Try it, and come back if you get stuck with something more specific - and include your code
    – musefan
    Commented Jan 3, 2014 at 10:19

4 Answers 4

3

Try

window.location.hash = '#divname';

Where #divname is the id of your div

2
  • 1
    I've tried this method and found in Chrome (Version 31.0.1650.63) that the location.hash only works once. E.g. If a user is scrolled to an anchor then moves away and wants to be scrolled back to the same anchor it doesn't work. location.href seems to work always. Here's a Fiddle, I don't know if the same happens on other browsers.
    – AeroX
    Commented Jan 3, 2014 at 10:33
  • 1
    @AeroX this is a solution for you jsfiddle.net/cmhN5/3. Just add an anchor that is not used location.hash = 'anchornotused';
    – laaposto
    Commented Jan 3, 2014 at 11:51
1

Can you try this,

<body onload="window.location.hash = '#divname';">
1

That is called bookmark links, see here http://www.hyperlinkcode.com/bookmark.php.

To navigate to an anchor via javascript you can use this code:

window.location.hash = "#divname";

This topic is also a duplicate of the following: How to scroll HTML page to given anchor using jQuery or Javascript?

Regards.

1

If you want to browse directly using a URL (as per your question), then there is absolutely no need for any javascript.

All you need to do is set an id for your div elements, that match the anchor tag you want to use. In the case of your example:

www.xyz.com/#divname

Then you would need an element like so:

<div id="divname">
</div>

Here is a working example

Not the answer you're looking for? Browse other questions tagged or ask your own question.