Search code examples
javascriptjquerywindow

Change Window location dynamically by #id - Jquery/Javascript


I have url like this -

http://test.com/simple-post#5

Here #5 will change dynamically. My html divs are many like

<div id=1> Div 1 </div>
<div id=2> Div 2 </div>
....
<div id=5> This </div>

So, when page loads windows location will go that div by id. How can I do that using Jquery/Javscript?

I know in jquery I can redirect window location by window.location

$(document).ready(function () {
    window.location = "#";
});

Please tell me if there is other efficient way to do this.


Solution

  • It should go actually with your current code without any script.

    If that is not working and you want to do it with script, you can do

    $(document).ready(function () {
        var afterhash = location.hash.substr(1);
        $('html, body').animate({scrollTop:$('#'+afterhash).position().top}, 'slow');
    });