Super newb question here, but my brian is not working tonight. I'm using a provided JS script on a wordpress site to make a single-page website menu scroll to the relevant section.
I have a menu with options 'Home' 'People' 'Info' 'Contact'
These links are structured like so: " http://sample.com/#home "
<!-- Navigation Menu -->
<div class="collapse navbar-collapse" id="navigation">
<ul id="menu-menu-1" class="nav navbar-nav navbar-right"><li id="menu-item-15" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-15">
<a href="http://sample.com/#home">Home</a></li>
<li id="menu-item-51" class="menu-item menu-item-type-custom menu-item-object-custom menu- item-51">
<a href="http://sample.com/#people">People</a></li>
<li id="menu-item-14" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-14">
<a href="http://sample.com/#info">Info</a></li>
<li id="menu-item-54" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-54">
<a href="http://sample.com/#contact">Contact</a></li>
</ul>
</div>
<!-- End Navigation Menu -->
The JS follows below.
//Navigation Scrolling
$('#navigation a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
The problem: When clicking the menu-links, the page reloads and shows the relevant section.
I would like the menu items to scroll to the relevant section instead.
Thanks.
TL;DR Menu items reload page instead of scrolling to relevant section. JS above.
Just prevent the default functionality of the anchor tag by using event.preventDefault()
,
$('#navigation a[href*=#]').click(function(e) {
e.preventDefault();
//Rest of your code
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.