Cannot run script properly with my custom plugin

I’m pretty new with wordpress developing. What I’m trying to do is to add javascript to my plugin. It seems to be loaded, because when I’m console loging something like ‘test’ it works fine. But when I’m trying to query anything (for example document.querySelector(‘#only-for-test’)) or even (‘body’), it gives me back ‘null’…

function addThemeStyles() {
  wp_enqueue_style('style_file' , plugin_dir_url(__FILE__).'plugin_styles.css');
}

function addThemeScript() {
  wp_enqueue_script('js-file', plugin_dir_url(__FILE__).'plugin_pj_script.js');
}

function todoPJ_enqueueBootstrapCSS()
{
    // CSS
    wp_register_style('prefix_bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css');
    wp_enqueue_style('prefix_bootstrap');
}

function testFunction() {
  // $test = plugin_dir_path('styles.css');

  return '
  <div class="another-test-file" id="only-for-test">
    <div class="container">
      <div class="row">
        <div class="col-6">
          <h1>Hello World!</h1>
        </div>
        <div class="col-6">
          <h1>Another Hello World!</h1>
        </div>
      </div>
    </div>
  </div>';
}


add_action('wp_enqueue_scripts', 'addThemeStyles');
add_action('wp_enqueue_scripts', 'addThemeScript');
add_action('wp_head', 'todoPJ_enqueueBootstrapCSS');

add_shortcode('example', 'testFunction');

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I figured this out, maybe it will help someone – probably, my script was loading on the header, so html was loading after script fired. What I did was adding those few parameters, where this last ‘true’ is the most important (moves script to footer). Hope this helps to anyone

  wp_enqueue_script('js-file', plugin_dir_url(__FILE__).'/js/plugin_pj_script.js', '', '1.0.0', true);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x