how to add Jquery script to one page?

What is the best practice to apply an individual script to a particular page? When I try to apply the script of the whole page it has problems with other plug-ins. Is there a rule of thumb?

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


<script>

(function() {

$('html').addClass('js');

var contactForm = {

    container: $('#contact'),

    config: {
        effect: 'slideToggle',
        speed: 500
    },

    init: function(config) {
        $.extend(this.config, config);

        $('<button></button>', {
            text: 'Contact Me'
        })
            .insertAfter( 'article:first' )
            .on( 'click', this.show );
    },

    show: function() {
        var cf = contactForm,
            container = cf.container,
            config = cf.config;

        if ( container.is(':hidden') ) {
            contactForm.close.call(container);
            container[config.effect](config.speed);
        }
    },

    close: function() {
        var $this = $(this), // #contact
            config = contactForm.config;

        if ( $this.find('span.close').length ) return;

        $('<span class=close>X</span>')
            .prependTo(this)
            .on('click', function() {
                // this = span
                $this[config.effect](config.speed);
            })
    }
};

contactForm.init({
    // effect: 'fadeToggle',
    speed: 300
});

})();

</script>

Related posts

Leave a Reply

2 comments

  1. I usually register all the scripts I need using wp_register_script and then use wp_enqueue_script inside a conditional for scripts that need to be loaded only on specific pages.

    functions.php

    function enqueue_scripts() {
        wp_register_script( 'global', get_template_directory_uri() . '/lib/js/global.js', array( 'jquery' ), '1.0', true );
        wp_register_script( 'example', get_template_directory_uri() . '/lib/js/example.js', array( 'jquery' ), '1.0', true );
    
        wp_enqueue_script( 'global' );
    
        if ( is_page( 2 ) ) { // example page
            wp_enqueue_script( 'example' );
        }
    }
    
    add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );