Own js document

Hello

Example If i want to create another .js document and link it only on a specific page like www.site.com/about-us

This .js file will have a eventListener that makes a title turn red if a user clicks on it (just as an example).

So… How do i add this javascript file to a specific page?

the file root is “wordpress/wp-content/themes/sydney-child/js/testscript.js”

Hello there,

Try adding the following function into your child theme’s functions.php:


function sydney_child_scripts(){

  if(is_page('about-us')){ // Page slug: about-us
    wp_enqueue_script( 'sydney-child-custom-js', get_stylesheet_directory_uri() . '/js/testscript.js', array('jquery'),'', true );
  }

}
add_action( 'wp_enqueue_scripts', 'sydney_child_scripts' );

Regards,
Kharis

Would it be bad to just add this at the bottom of the body of the page?

<script src="/wp-content/themes/sydney-child/js/testscript.js"></script>

Hello there,

Technically it works, but it isn’t recommended way to do. Please see the theme handbook for more detailed information about it.

Regards,
Kharis