I have a navbar that links to different anchors on the startpage. and when i use the links in the nav on the startpage it smoothly scrolls to the right ID. but when i go to a sub-page/other page i want the navbar to send me directly back to the startpage and the choosen ID(anchor). i think there is some conflict with the smooth-scroll javascript but i could be wrong.
name of my custom WP-theme is: fitnesstravels.
the navbar is made of custom links from Wordpress menu ex:
url: http://localhost:8080/fitnesstravels/#destinations
name: Destinations
when i go to a subpage like: http://localhost:8080/fitnesstravels/destinations/rhodos
the menu-link in my navbar named "Destinations" is linked to the http://localhost:8080/fitnesstravels/#destinations
anchor (if i right klick "open link in new tab" i get send to the right place. but nothing happens when im trying simply using the menu-link.
the js:
$('.nav.navbar-nav a, .arrow a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top-50
}, 1200, 'swing', function () {
window.location.hash = target;
});
});
The problem is the e.preventDefault()
.
I've done exactly what you are trying to do on a site, and in the same way you described, the only significant difference being that my smooth scroll jQuery doesn't use preventDefault
.
This is (the relevant section of) my smooth scrolling jQuery:
var $root = $('html, body');
$( ".navbar" ).on( "click", "li a", function( ) {
var pageanchor = this.hash;
if (pageanchor)
$root.animate({ scrollTop: $(pageanchor).offset().top}, 500);
});
If I change my code to use your variable names and animation settings, it is almost identical to yours except for the preventDefault
.
$(document).ready(function() {
$('.nav.navbar-nav a, .arrow a[href^="#"]').on('click',function (e) {
var target = this.hash;
if (target)
$('html, body').animate({
scrollTop: $(target).offset().top-50
}, 1200, 'swing', function () {
window.location.hash = target;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.