Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add Wordpress php code into JavaScript

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.

like image 216
Jamdev Avatar asked Oct 18 '18 08:10

Jamdev


People also ask

Can we add PHP code in JavaScript?

Yes, you can, provided your JavaScript code is embedded into a PHP file.

Can I use WordPress with JavaScript?

JavaScript can be used within the WordPress platform to add dynamic elements to pages and posts, or across your entire website.

Does PHP work with JavaScript?

JavaScript can also talk with your PHP code on the web server whenever it needs to update something (either on the server or on the web page).


1 Answers

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)

    }
});
like image 165
Vasyl Zhuryk Avatar answered Oct 13 '22 08:10

Vasyl Zhuryk