0

so i wrote a simple script and enqueued it properly.

my-jquery-script.js:

jQuery(document).ready(function($) {
$('#some_id').on('click','.clone',function(e){
alert('clicked');
/*.....*/
e.preventDefault();
});
});

functions.php:

add_action( 'wp_enqueue_scripts', 'my_function' );

function my_function() {

wp_enqueue_script( 'my-jquery-script', get_stylesheet_directory_uri() . '/js/my-jquery-script.js' );

}

some-page.php:

<?php wp_head(); ?>
<body>

<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
</form>

</body>
<?php wp_footer(); ?>

it's not working but when i include jQuery script manually into some-page.php like this:

<?php wp_head(); ?>
<body>

<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
<script type='text/javascript' src='<?php echo get_stylesheet_directory_uri() . "/js/my-jquery-script.js"; ?>'></script>
</form>

</body>
<?php wp_footer(); ?>

it's working but "$(document).ready () fires twice" as mentioned here: https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice

What am i doing wrong? Any help would be appreciated.

update: I also noticed that $(document.body).on('click','.clone',function(e){ } selector is working instead of id selector.

2

If your script depends on jQuery, you have to declare that dependency to make sure WordPress will enqueue it earlier than yours.

wp_enqueue_script( 
    'my-jquery-script', 
    get_stylesheet_directory_uri() . '/js/my-jquery-script.js',
    [ 'jquery' ] /* declare the dependency */
);
  • tried wp_enqueue_script( 'my-jquery-script', get_stylesheet_directory_uri() . '/js/my-jquery-script.js', array('jquery') ); but no luck. I also noticed that $(document.body).on('click','.clone',function(e){ } selector is working instead of id selector. Sad thing that i need to select id's! – user2397435 Aug 28 '16 at 21:11
0

I ended up changing theme and it resolved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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