• Resolved Cantoga

    (@cantoga)


    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', array('jquery') );
    
    }

    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: http://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.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    Hi there!

    One of the things I noticed from the thread you linked to was:

    What is more than likely happening is you have code that is moving or manipulating the element that the code is contained within

    Are you able to provide a link to the site?

    Thread Starter Cantoga

    (@cantoga)

    Hi Jose,
    Unfortunately i’m working on localhost. What confuses me is $(document.body).on(‘click’,’.clone’,function(e){ } triggers like a charm while $(‘#some_id’).on(‘click’,’.clone’,function(e){ } is not responding at all. I don’t know maybe i’m missing quite basic thing.

    Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    Are you able to post just the first few lines where the wp_head() is located. At least up to the closing </body> part. 🙂

    You can try updating your code to something like this

    (function ( $ ) {
    
       $(document).ready(function() {
           $('#some_id').on('click','.clone',function(e){
                  alert('clicked');
                  e.preventDefault();
            }); // This closing parenthesis was missing as well
        });
    
    }( jQuery ));

    Thread Starter Cantoga

    (@cantoga)

    I ended up with changing theme. Thank you all.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘jQuery script is not working inside 'head' tag’ is closed to new replies.