Reputation: 552
I have the following javascript code:
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src','assets/images/logo.png'); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src','assets/images/logo__footer.png')
}
});
Is it possible to insert a wp custom php code
<?php the_custom_logo(); ?>
Instead of this static attribute
.attr('src','assets/images/logo.png');
Many thanks in advance.
Upvotes: 5
Views: 77
Reputation: 5211
IF you need jquery with php code input then wp_localize_script()
function.
More information
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'logo_image' => the_custom_logo(),
'logo_image_footer' => the_custom_logo()'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
You can access the variables in JavaScript as follows:
<script>
alert( object_name.logo_image);
alert( object_name.logo_image_footer);
</script>
$('.navbar-brand img').attr('src',object_name.logo_image); //change src
Upvotes: 1
Reputation: 972
Your Js code:
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src','custom_logo.png'); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src','logo_footer.png')
}
});
HTML code:
<?php $customLogo= 'custom_logo'; ?>
<?php $footerLogo= 'footer_logo'; ?>
<html>
<body>
<script type="text/javascript">
// notice the quotes around the ?php tag
var customLogo="<?php echo $customLogo; ?>";
var footerLogo="<?php echo $footLogo; ?>";
alert(customLogo);
alert(footerLogo);
</script>
</body>
</html>
Upvotes: 1
Reputation: 1248
You need to set variable in template:
<script>
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
</script>
and than, in your js file use it
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src',logoImage); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src',logoImageFooter)
}
});
Upvotes: 5