I'm using javascript to control where my page page scrolls to after clicking on an anchor link, as I have a fixed nav.
I have one page that the anchors + script work correctly on (PAGE B). My issue is that I have buttons on a different page (PAGE A) that need to go the anchors on the correctly working page (PAGE B). The anchor itself works correctly, but the javascript does not fire.
The reason why it's not firing (tested by putting an alert and not receiving a popup) is because the javascript for the buttons on PAGE A does not know to look for the element on PAGE B. After googling for three hours I cannot figure out how to tell it to look at a new page instead of just the hierarchy of elements. I'm sure this is stupidly simple, but I'm a beginner at javascript and appreciate the help.
The code:
PAGE A Button HTML:
<a href="productsandservices.html#financing" class="btn btn-sm btn-default
actively2">Learn more</a>
PAGE A Javascript:
<script>
$("div ul li a[href^='productsandservices.html#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 150
}, 300, function(){
});
});</script>
PAGE B Anchor HTML:
<div class="col-md-10 col-md-offset-1 col-sm-12 col-xs-12"><section id="financing">
PAGE B: Javascript: (the exact same as PAGE A)
$("div ul li a[href^='productsandservices.html#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 150
}, 300, function(){
});
});</script>
Please and Thanks.
Page B will never be able to respond to a click event on the previous page, which seems to be what you're trying to do in the code.
Try using location.hash
to access the hash instead.
$(window).on('hashchange', function(e) {
$('html, body').animate({
scrollTop: $(location.hash).offset().top - 150
}, 300);
});