I was trying to store the template url (bloginfo(template_url);) into a variable so I could use it in my JavaScript. However, I realized this wasn't possible and someone alerted me to wp_localize_script and said that it could do what I wanted. I looked through the codex but I'm still unsure as to how to implement this.
Here's what I have so far:
Function
function starter_scripts() {
wp_enqueue_script( 'jquery' );
wp_localize_script( 'my_script', 'templateUrl', array(
'templateUrl' => template_url()
) );
}
add_action( 'wp_enqueue_scripts', 'starter_scripts' );
JS
jQuery(document).ready(function($){
// Fade in Contact background
$('body.page-template-page-contact #content').css('background', 'url(templateUrl + bg-contact.jpg) 50% 0% no-repeat fixed').fadeIn(2000);
});
Where have I gone wrong?
Update:
function starter_scripts() {
wp_enqueue_style( 'starter-style', get_stylesheet_uri() );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'includes', get_template_directory_uri() . '/js/min/includes.min.js', '', '', true );
wp_localize_script( 'includes', 'site', array(
'url' => site_url('/'),
'theme_path' => get_template_directory_uri(),
'templateUrl' => template_url()
) );
}
add_action( 'wp_enqueue_scripts', 'starter_scripts' );
JS
jQuery(document).ready(function($){
// Fade in Contact background
$('body.page-template-page-contact #content').css('background', 'url(site.templateUrl/img/bg-contact.jpg) 50% 0% no-repeat fixed').fadeIn(2000);
});
'url(site.templateUrl + bg-contact.jpg)is kind of wrong.'url(' + site.templateUrl + 'bg-contact.jpg)should work a bit better though.