enqueue javascript

1 Reply ·

  1. My aim is to enable automatic scrolling on page load on some single pages and posts.
    I have the following script

    $(document).ready(function(){
        var scroll= $(window).scrollTop();
        scroll= scroll+ 500;
        $('html, body').animate({
            scrollTop: scroll
        }, 1000
    });
    

    in a file named onpageload.js.

    I only want it to load on single pages or single posts (but not the frontpage or blogpage) that have a featured image.

    The file is located in a childtheme folder
    railtrail/assets/js/onpageload.js

    Could you help with this?

  2. Justin Tadlock

    I’m assuming railtrail is the child theme folder name.

    The following code should do the trick:

    add_action( 'wp_enqueue_scripts', 'th_enqueue' );
    
    function th_enqueue() {
    
        if ( ! is_front_page() && is_singular( array( 'post', 'page' ) ) && has_post_thumbnail( get_queried_object_id() ) ) {
    
            wp_enqueue_script( 'th-onpageload', get_theme_file_uri( 'assets/js/onpageload.js' ), array( 'jquery' ) );
        }
    }