Scott B
Scott B

Reputation: 40157

How do I change a hardcoded path to a dynamic one in javascript?

I'm using the jpicker color picker widget with my theme. Inside the js file I've had to hardcode the reference to the jpicker's images folder like so...

images:{clientPath: '../wp-content/themes/MyThemeFolder/js/jPicker/images/',

I would like to redo this to by more dynamic in case the user changes the name of the theme folder.

Any ideas? URL parsing?

UPDATE: Here's what I had to do to resolve it...

Inside of functions.php and just before the js script is included, I placed this...

<script type="text/javascript">
<?php echo 'var myThemePath="../wp-content/themes/'.get_option("template").'/js/jPicker/images/"';?>
</script>

Then, inside the .js file, I did a replace on the hardcoded directory path so that this...

images:{clientPath: '../wp-content/themes/MyThemeFolder/js/jPicker/images/',

Becomes this...

images:{clientPath: myThemePath,

Upvotes: 2

Views: 1747

Answers (1)

Pekka
Pekka

Reputation: 449395

What I like to do is to save the web root URL (or media/resources folder URL or whatever) in a global JS variable before including external scripts:

 <script type="text/javascript">
 my_project_web_root = "http://example.com";
 </script>

and use that in all subsequent scripts:

 images:{clientPath: my_project_web_root+'/wp-content/themes/MyThemeFolder/...'

Upvotes: 1

Related Questions