Smooth anchor scrolling with Wordpress Visual Composer onclick javascript action button feature

John Blignaut picture John Blignaut · Apr 13, 2017 · Viewed 12.2k times · Source

I'm using Wordpress Visual Composer and would like a button to have a smooth scroll down to a specific section on the same page.

I've explored the standard button element's "insert inline onclick javascript action" with anchor IDs and code from many other similar Q&As, but have had no luck. Does anyone have the answer specifically to Wordpress Visual Composer?

(Below are screenshots of how I tried to implement @Frits suggestion.)

Button href

Raw JS block

Answer

Frits picture Frits · Apr 13, 2017

In future, adding your current attempt is a great idea as it will help us adjust your code. You've clearly tried some things, they clearly didn't work (else you wouldn't have come here) - show us what you tried, and we might be able to help you fix your current attempt!

Anyways, on to the actual code.

Seeing as you are missing a bit of information, I am going to have to make a few assumptions.

I am going to assuming that you have a button that looks like this:

<a href="#my-visual-composer-row-id" class="my-link">Click here to scroll down</a>

and I am going to assume that you have given your visual composer row an ID of my-visual-composer-row-id (you can do this under the edit options on the actual row itself)

If you're ok with using jQuery, you can then implement the following either in a RAW JavaScript block somewhere (preferably the bottom of the page), or if you're making your own theme, you can add this to your .js file.

jQuery(document).ready(function($){
    $('.my-link, .my-link a').click(function(e){
        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: Math.ceil(target.offset().top) 
                }, 1000);
            return false;
            }
        }
    });
});

this has been adapted from the CSS-Tricks smooth scrolling solution which can be found here.