Site logo

Archived topic

Smooth Scroll

1 reply · Started by Sebastián on December 1, 2017

Viewing posts 1–2 of 2

So.. i tried to make it work without your help but i can't.

First I added this to my wp_footer hook:

add_action( 'wp_footer', 'tu_add_script' );
function tu_add_script() { ?>
    <script>
jQuery(function($) {
	$(document).on('click', 'a[href*="#"]:not([href="#"])', function(e) {
		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) {
				e.preventDefault();
				$('html,body').animate({
					scrollTop: target.offset().top
				}, 500);
			}
		}
	});
});
</script>
<?php }

Then I activated execute php.

After that I added this to the link:

<a href="whatever" class="smooth">Link</a>

But it didn't work.

Im not good at coding but this is how it looks like (in general):

<a href="#primero" class="smooth">Miedo a fracasar</a>

And then this to the h3 where i want the user to go in the same page:

<h3 id="primero"> <strong>Miedo a Fracasar</strong></h3>

This is the page where i tried: https://sebastiancardozo.com/negocios-rentables-por-internet/

Maybe you know what kind of mistake im making.

Thanks!

Hi there,

I just used this script in the wp_footer hook:

<script>
    jQuery('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
            || location.hostname == this.hostname) {

            var target = jQuery(this.hash);
            target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']');
               if (target.length) {
                 jQuery('html,body').animate({
                     scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
</script>

Then you you should able to add the link normally like:
<a href="http://SITE-URL/#ANCHOR-ID">Text</a>

This archived topic is closed to new replies.