jQuery function didn’t work in my plugin

I create my first WP plugin. Firstly, I add div, h1 and button to single post and below this I try to hide this div after clicking button. I try do this by adding external jQuery file. The problem is that after clicking button nothing happened. I dont know why.

My PHP code:

add_filter('the_content', 'hello_world_date_time');

function hello_world_date_time() {
    if ( is_single() ) {
        echo '<div id="container-post">';
        echo '<h1>' . 'Hello, world!' . '</h1>';
        echo '<p>' . 'Opublikowano o godzinie: ' . '</p>';
        echo the_time('g:i a'); 
        echo '<br>';
        echo '<button id="hide">UKRYJ</button>';
        echo '</div>';
    }
}

add_action('wp_enqueue_scripts', 'hide_container_post');

function hide_container_post() {
    wp_enqueue_script('MyScript', plugins_url('/script.js', __FILE__), array('jquery'), false, true );

}

jQuery code:

$(document).ready(function() {
    $("#hide").click(function() {
        $("#container-post").hide();
    });
});

1 Answer
1

Instead of using:

$(document).ready(function() {
    $("#hide").click(function() {
        $("#container-post").hide();
    });
});

use:

jQuery(document).ready(function($) {
    $("#hide").click(function() {
        $("#container-post").hide();
    });
});

Leave a Comment