Add javascript to Wordpress plugin

2

I registered my Javascript file in my plugin, but the functions of click and so on. do not work.

I registered my main plugin file with action :

function add_scripts_to_plugin()
{
     wp_enqueue_script( 'birthdate_celebrate_js', dirname(__FILE__) . '/includes/assets/js/main.js', array( 'jquery' ));
}
add_action('wp_enqueue_scripts', 'add_scripts_to_plugin');

The Javascript file:

jQuery( function( $ ) {
    $('#birthdate_celebrate_send_mails').on('click', function () {
        console.log('clicked');
    });
});

The plugin loads normally and does not display any errors in the console or in PHP, but even then the eventListener of click is not added to the button.

    
asked by anonymous 11.07.2017 / 16:55

3 answers

4

I found the answer in this stack topic .

To include the file with wp_enqueue_script that is a plugin , you should use the function plugin_dir_url and not get_template_directory_uri() , because this function returns a URL that points to the current theme which is being used.

Resolution:

function birthdate_celebrate_add_interactions_to_plugin()
{
    wp_enqueue_script( 'birthdate_celebrate', plugin_dir_url( __FILE__ ) . 'includes/assets/js/birthdate_celebrate.js', array( 'jquery' ), '1.0');
}
add_action('admin_enqueue_scripts', 'birthdate_celebrate_add_interactions_to_plugin');
    
20.07.2017 / 21:35
2

I see two things that can potentially cause a problem there, but nothing guarantees they are. The first is to use dirname(__FILE__) instead of get_template_directory_uri() :

function add_scripts_to_plugin()
{
     wp_enqueue_script( 'birthdate_celebrate_js', get_template_directory_uri() . '/includes/assets/js/main.js', array( 'jquery' ));
}
add_action('wp_enqueue_scripts', 'add_scripts_to_plugin');

The second is to put a click event on an element that is on the page from the page load, and delegate to the button:

jQuery( function( $ ) {
    // troque 'body' por um outro seletor mais próximo, talvez um pai direto do botão que quer alcançar.
    $('body').on('click', '#birthdate_celebrate_send_mails' , function () {
        console.log('clicked');
    });
});
    
19.07.2017 / 22:25
1

Your code is correct, I ran a test on a page with just one button with that id and it worked.

See if at the time you try to attach the event the object already exists, first put a statement to print the result of $('#birthdate_celebrate_send_mails') :

jQuery( function( $ ) {
    console.log($('#birthdate_celebrate_send_mails'));
    $('#birthdate_celebrate_send_mails').on('click', function () {
        console.log('clicked');
    });
});

Another way to do it, if the object is included later, would look like this:

    $(document).on('click', '#birthdate_celebrate_send_mails', function () {
        console.log('clicked');
    });
    
19.07.2017 / 21:29