WordPress.org

Ready to get started?Download WordPress

Forums

How to find the theme path from within a javascript file of a theme in WordPress (6 posts)

  1. sixfootjames
    Member
    Posted 2 years ago #

    Hi,

    I am trying to figure out why I cannot find the path to an image I am trying to set within my js file. Here's my setup..

    footer.php

    `<script language="javascript" src="<?php
    bloginfo('template_directory'); ?>/js/scripts.js"></script>
    </body>`

    themes/themename/js/scripts.js
    `var imageUrl = "../images/sprite-site.png";
    $j(this).css('background-image', 'url(' + imageUrl + ')');`

    I've tried 10 different options and none have worked so far.

    I would appreciate some help with this please.

  2. sixfootjames
    Member
    Posted 2 years ago #

    Strangely enough, if I check the url in Firebug, it is to the right path when I compare it to another element's background image.

    If I copy and past the background image from the element that DOES work, to the element which doesn't work, the background image is not found.

  3. esmi
    Forum Moderator
    Posted 2 years ago #

    I'd suggest enqueuing your script correctly and always, ALWAYS, using absolute urls in any path variables.

  4. sixfootjames
    Member
    Posted 2 years ago #

    Thanks Esmi. This is what I am trying and still I don't find it works

    function my_scripts_method() {
    wp_enqueue_script(
        'myscript',
        get_bloginfo('template_directory') . '/js/scripts.js',
        array( 'jquery' ),
        '',
        true
    );
     }
     add_action('wp_enqueue_scripts', 'my_scripts_method');

    Is there something else I might be missing?

  5. sixfootjames
    Member
    Posted 2 years ago #

    Would absolute urls not be a living nightmare to fix once you move from localhost to development?

    I am assuming you then mean that...

    get_bloginfo('template_directory') . '/js/scripts.js',

    should then be changed to

    'http://www.example.com/wp-content/themes/themename/js/scripts.js',

    ??

  6. esmi
    Forum Moderator
    Posted 2 years ago #

    Would absolute urls not be a living nightmare to fix once you move from localhost to development?

    They can be but that's true of WordPress generally, I'm afraid.

    <script language="javascript" src="<?php
    bloginfo('template_directory'); ?>/js/scripts.js"></script>
    </body>

    needs to be replaced by a wp_enqueue in your theme's functions.php file. The absolute url I was referring to is in :

    var imageUrl = "../images/sprite-site.png";
    $j(this).css('background-image', 'url(' + imageUrl + ')');

Topic Closed

This topic has been closed to new replies.

About this Topic