1

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>
2
  • Is that for fron-end or back-end? And why do you use an outdated jQuery instead of the built-in version?
    – fuxia
    Commented Oct 3, 2012 at 3:12
  • front end for a slider. I'm working one tutorial that is a few months old and that is probably why I'm referencing the outdated J query version. Thanks for your response. Commented Oct 3, 2012 at 13:56

2 Answers 2

1

This url works
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
and for particular page you can use

if( is_page('x')) { ?>
// YOUR SCRIPT STUFF
<?php }
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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.