woocommerce, overwrite auto scroll (scroll to notice function)

It is WooCommerce default behaviour to scroll to the top of the checkout or the cart form after an errored checkout submit.
I had a case where the auto scroll didn’t scroll to the right position so the errors were always hidden. The auto scroll code is located in the file woocommerce.js, here what I used to overwrite it, adding an offset :

// overwrite woocommerce scroll to notices
$.scroll_to_notices=function( scrollElement ) {
     var offset = 300;
     if ( scrollElement.length ) {
     $( 'html, body' ).animate( {
          scrollTop: ( scrollElement.offset().top-offset )
          }, 1000 );
     }
};

 

3 Comments

  • Andi says:

    Nice workaround ! Good job.
    I do have Rife theme and woocommerce installed and using a fixed header.
    The approach seems to work for me as well. But Where is woocommerce.js originally located on the server?
    wp-content/plugins/woocommerce/assets/js/ does not contain the woocommerce.js as i would have expected it there.

    Will the change stay there after an woocommerce or template update?

    Have you seen a good solution to “wp_enqueue_script”

    • Trân says:

      Hi Andi,

      you should write this code in your own js file, the one from your template. That way, even if you update woocommerce the change is going to stay.

  • Johnny says:

    Awesome! Thanks for this – this has been bugging me for a while on my website. I don’t understand why WooCommerce can’t make this configurable out of the box for people that have fixed headers. There is no documentation.

    By the way, I added this exact code to the HTML footer during checkout so that the automatic scroll to top now shows the error messages:

    $data = ”
    jQuery( function( $ ) {
    $.scroll_to_notices = function( scrollElement ) {
    var offset = 300;
    if ( scrollElement.length ) {
    $( ‘html, body’ ).animate( {
    scrollTop: ( scrollElement.offset().top-offset )
    }, 1000 );}};});”;
    wp_register_script( ‘dummy-handle-footer’, ”, [], ”, true );
    wp_enqueue_script( ‘dummy-handle-footer’);
    wp_add_inline_script( ‘dummy-handle-footer’, $data );

Leave a Reply

Your email address will not be published. Required fields are marked *