0

I have two files:

abc.php

<?php
/*
Template Name:ABC Template
*/
?>
<div id="div-image" class="div-child"> <img src="<?php echo get_template_directory_uri(); ?>/Images/Loading.gif" id="load" /> </div> 
 <script src="<?php echo get_template_directory_uri(); ?>/alphawords.js" type="text/javascript"></script>

xyz.js

document.getElementById("load").src="<?php echo get_template_directory_uri(); ?>/Images/pic.png";

xyz.js is included properly, but image is not being loaded through the JS. How can I get the image to load properly?

Thank you in advance.

2 Answers 2

0

You don't seem to have a trigger for your JS. You can test that the script is actually running by adding a quick console, such as

console.log('xyz.js is running');

Once you're sure your JS is running, you can add a trigger. If you're already loading jQuery, it has an easy .ready() function to use, but if not, there are other ways.

It's also best practice to enqueue your JavaScript, instead of adding <script> tags directly. See wp_enqueue_script(). You may want to do this before adding your console and before adding the trigger, as really enqueueing is the first step.

0

It seems like you're trying to use PHP inside a JS file, which won't work. Instead, you'll need to pass the dynamic path to your JS file from PHP using wp_localize_script() which can be used on enqueued and registered scripts like this:

function custom_enqueue_script() {
    wp_enqueue_script(
        'custom-xyz', // Handle
        get_template_directory_uri() . '/xyz.js',
    );
    wp_localize_script(
        'custom-xyz', // Handle
        'my_object', // Object variable name
        array('theme_dir' => get_template_directory_uri()) // Properties and values
    );
}
add_action('wp_enqueue_scripts', 'custom_enqueue_script');

And then in the xyz.js file, the my_object is an object variable available to you.

document.getElementById("load").src = my_object.theme_dir + "/Images/pic.png";

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.