0

I have a website that has anchor links on the front page that link to different sections of the page. I have ran into an issue with the secondary pages where whenever they click on the anchor links that reference the sections on the main page it does not take them to the section. I have tried to use the full URL http://www.website.com/index.php#1 but that only takes be to the main page but does not trigger the location of the anchor link. Is there something i'm missing?

I'm using the following Jquery for the smooth scroll and to activate a menu rollover whenever they are at a certain section.

<script>
var timerid; //Used to fire scroll function once after scrolling is done.
$(document).ready(function(){
$("#menu-main-menu a").click(function(e){
    e.preventDefault();
    $("#menu-main-menu a").removeClass('active');
    var id = $(this).attr("href").substring(1);
    $("body").animate({
        'scrollTop': $("section#" + id).offset().top -133
    });        
});
$("body").scrollTop(1); //forcing window scroll to execute on page load
$(window).scroll(function(){
    clearTimeout(timerid);
    timerid = setTimeout(checkactivelink, 50);
});

function checkactivelink()
{
    $("section").each(function(){
        if($("body").scrollTop() >= $(this).offset().top -133)
        {
            $("#menu-main-menu a").removeClass('active');
                $("#menu-main-menu a[href=#" + $(this).attr("id") + "]").addClass('active');
        }
    });
}
});
</script>
Ty T.
  • 586
  • 5
  • 18
  • `$("body").scrollTop(1)` is overriding the normal scroll down to the anchor in the URL. – Barmar Aug 12 '14 at 16:50
  • So would I remove this? Or would there be a better way to go about this? – Ty T. Aug 12 '14 at 16:53
  • Tie your code to the [`hashchange`](http://stackoverflow.com/questions/680785/on-window-location-hash-change) event instead of `click`, then `.trigger('hashchange')` on `$(document).ready` – Blazemonger Aug 12 '14 at 16:57
  • I guess i'm still doing something wrong because its still not working. All I want is whenever someone clicks on students and goes to the students page. And then they click the top links they will go back to the home page and down to the appropriate anchor area. Example Link: http://gr8students.wpengine.com – Ty T. Aug 12 '14 at 17:11

1 Answers1

0

Try replacing

$("body").scrollTop(1);

with:

if(location.hash) {
    $("#menu-main-menu a[href='"+location.hash+"']").click();
}

So when you open the page with an anchor in the link, it will emulate clicking on the corresponding navigation menu.

Barmar
  • 741,623
  • 53
  • 500
  • 612