user1576978
user1576978

Reputation: 1755

Check active div onload

I'm using something like this in a layout

<nav id="main-nav">
   <a href="#link1">Link1</a>
   <a href="#link2">Link2</a>
   <a href="#link3">Link3</a>
</nav>
<div id="link1">
   some content goes here
</div>
<div id="link2">
   some content goes here
</div>
<div id="link3">
   some content goes here
</div>

So when i click on some nav link it scrolls down to the correct div. The thing is that NAV is a fixed positioned menu, and it uses 200px from the top. the JS i use to scroll is this:

$('#main-nav a').click( function(event) {
    var nome = $(this).attr("href");
    $('html, body').animate({
         scrollTop: $(nome).offset().top-198
     }, 1600);
});

Ok, so there's this internal page, where the nav links become:

<a href="http://www.mysite.com/#link1">Link1</a>

The problem is that it loads the home ok, but the div starts from top, under the NAV (because there's no offset().top-198 when it loads the page.) I think what i need is to find a way to get the #link from the url that loads and make a onLoad scrollTop, is that right?

Any helps please?

Upvotes: 1

Views: 1022

Answers (2)

dev
dev

Reputation: 4009

You could use something similar to the below, that finds the current hashtag in the URL and then matches it to a divs ID and then animates that ID.

$(function(){
   currentPage = window.location.hash;
   moveLink =  $('div').find($(this).attr('id',currentPage));
   $('html, body').animate({
      scrollTop: $(moveLink).offset().top-198;
   });
});

EDIT---------------------------------------

var aniFunc = function(a){
   $('html, body').animate({
       scrollTop: $(a).offset().top-198;
   });
};

$(document).ready(function(){
   currentPage = window.location.hash;
   moveLink =  $('div').find($(this).attr('id',currentPage));
   aniFunc(moveLink);
}

$('#main-nav a').click( function(event) {
    nome = $(this).attr("href");
    aniFunc(nome);
});

Upvotes: 1

Julian Hille
Julian Hille

Reputation: 669

You could intitially do something like that:

window.location.href.match('(#.*$)')

and trigger a click on that element on page load.

Upvotes: 0

Related Questions