body onLoad on a specific WordPress page

…衆ロ難τιáo~ 提交于 2019-12-02 05:50:51
brasofilo

You don't need to apply the code to the <body> tag, see: https://stackoverflow.com/a/191318/1287812

This can be done in functions.php with the following code, and using the conditional tags mentioned by SrikanthAD:

add_action( 'wp_footer', 'b5f_on_load_script' );

function b5f_on_load_script()
{
    // Not our page, do nothing
    if( !is_page( 'about' ) )
        return;

    ?>
    <script type="text/javascript">
        window.onload = function() { alert( 'Inside specific page' ); };        
    </script>
    <?php           
};

Also see: How to use window.scroll to automatically scroll on pageload?

For some reason, I was having difficulties using the above approach, however the logic was correct.

I have now instead registered the scroll script separately and enqueued it based on page template using:

wp_register_script( 'scroll', get_template_directory_uri() . '/js/scroll.js' );
if( is_page_template('my-landing-page.php') ) wp_enqueue_script( 'scroll' );

With: window.onload=function(){window.scroll(0, 140)}; as a separate file.

Thanks for all the help.

You can use many of the conditional tags available in WordPress to get the desired functionality.

http://codex.wordpress.org/Conditional_Tags

Example:

 if ( is_page( 'about' ) ) { 
// do something
 } 

I agree with brasofilo, you don't necessarily have it include the conditional tag in your template. It can used anywhere, depending on your project.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!