0

I just deployed a new Wordpress site. Everything looks good, now I'm setting up jQuery:

Child theme functions.php:

//enqueue scripts
function my_theme_enqueue_scripts() {
    wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0');
    wp_enqueue_script('myjs');
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

Page template tpl-mypage.php:

<html>
    <head>
        <?php wp_head(); ?>   
    </head>
<body>
    <div id=”test-script”></div>
</body>
</html>

The js file my.js:

jQuery(document).ready(function( $ ){
    $("#test-script").html("Hello World");
})

This is NOT working. I can see my.js being loaded on Chrome>Inspect>Network.

What could be the problem here?

3 Answers 3

2

The code seems fine. Please check by loading the script in the footer and also use the wp_footer in your .php file.

1

Set the $in_footer argument to true when registering the script:

    wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0', true);

And also call wp_footer(), as Mohsin mentioned:

    <html>
        <head>
            <?php wp_head(); ?>   
        </head>
    <body>
        <div id=”test-script”></div>
    <?php wp_footer(); ?>
    </body>
    </html>
1
  • I have found the problem. It was THE QUOTE from <div id=”test-script”> versus $("#test-script").html("Hello World"); But thank you and @Mohsin Ghouri for pointing out my missing wp_footer(); I have added that too to make sure my js loads after the page.
    – Rollor
    Commented Feb 8, 2019 at 19:19
0

tried this way. No luck. need more help please. It works in locally but not inside wordpress.

My code : myjquery.js

   $(document).ready(function($) {

$('.item-type').click(function() { $('.item-type').removeClass('item-type-active'); $(this).addClass('item-type-active'); });

function rangeCalc(i) { var totalPrice = 0; var tariff = [{begin:1, price:1000}, ]; var tariffItem2 = [{begin:1, price:85}, {begin:3, price:80}, {begin:6, price:75}, {begin:11, price:70}, {begin:21, price:65}, {begin:61, price:60}];

tariff.forEach(function(num, item) { if (tariff[item].begin <= i) { totalPrice = tariff[item].price; $('.calc-total-price').text(i*totalPrice); $('.calc-price').text(totalPrice); };

}); };

$('.calc-range').on('input', function() { $('.calc-count').text(this.value); rangeCalc(this.value); });

});

loaded like this way. and shows it in page source.

function load_js_assets() { if( is_page( 292 ) ) { wp_enqueue_script('myjquery', '/js/myjquery.js', array('jquery'), '', true);

} 

}

add_action('wp_enqueue_scripts', 'load_js_assets');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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