Wordpress JQuery Smooth-scroll help needed please.

boeriebuffet

Senior Member
Joined
Aug 21, 2015
Messages
750
Reaction score
3
Location
Cape Town
Hi everyone, not sure if this is the right place for this question but I'm hoping some mastermind takes pity on me and provides me with a solution! Backstory - I created a one page Wordpress site about 2 years ago by googling for solutions/videos and after a week or two I then got it to work exactly as I expected and life went on... Fast forward to this lockdown weekend and I added an online store with WooCommerce (one page site, became one page + shop/category page + product pages + cart/checkout page.

When I setup the site originally I copied this JQuery from somewhere which provides a beautiful smooth scroll. Issue is this smooth-scroll is now somehow transferring to the WooCommerce product pages (as soon as the specific product page loads it auto scrolls past the product.

I don't really understand JQuery at all but the internal links on the homepage start with # so I'm not sure why the script still applies to other pages which don't start with or contains #? The other pages are as follows: ".co.za/shop" (no auto-scrolling); ".co.za/product-category/cat-one/" (no auto-scrolling); ".co.za/product/prod-one/" (this one auto-scrolls for some reason).

<script>
( function( $ ) {
$(document).on('click', 'a[href*="#"]:not([href="#"])', function(e) {
if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
var hashStr = this.hash.slice(1);
var target = $(this.hash);
target = target.length ? target : $('[name=' + hashStr +']');
if (target.length) {
$('html, body').animate({ scrollTop: target.offset().top -100}, 1000);
return false;
e.preventDefault();
window.location.hash = hashStr;
}
}
});
}(jQuery));
</script>
 
'a[href*="#"]:not([href="#"])

That's why...

The selector reads as follows:
All anchor tags with href # included but not href = # only.

You have two options.
Change your selector or change your code on every page.

Alternatively, remove jquery from your global js file and only include it locally on the pages you require smooth scrolling.
 
Top
Sign up to the MyBroadband newsletter