Inject some CSS containing PHP on JQuery

104

I am trying to get some CSS containing PHP on jQuery. I basically need this CSS:

background: #3c653c url( <?php echo $cta_background_image_url; ?> ) no-repeat fixed;

Applied to:

wp.customize( 'cta_background_image', function( value ) {
    var styles = {
          backgroundPosition : "center top",
          backgroundBlendMode: "hard-light",
          position: "relative",
          height: "440px",
          backgroundRepeat: "no-repeat",
          backgroundAttachment: "fixed",
          backgroundSize: "cover",
          lineHeight: "200%",
          color: "#fff",
          overflow: "hidden",
          paddingTop: "0",
          marginBottom: "0"
        };
    value.bind( function( to ) {
        $( '.cta-parallax-section ' ).css( 'background', 'url( ' + to + ')' );
        $( '.cta-parallax-section ' ).css( styles );
    } );
});

I need too inject the code where it says css( 'background', 'url( ' + to + ')' );

This code will be applied to a WordPress Customizer to make it render changes made by the user in real time within the preview window.

How can I achieve this? I can't find information online on this kind of maneuver.

Thanks in advance!

277

Answer

Solution:

To get the value from the variable$cta_background_image_url; you can simply set a timeout and retrieve the value from the element, which you can use for whatever you want.

For example:

setTimeout(function() {
    var data = $("background").css("background-image");
}, 50);

The variabledata would outputurl( [ value from $cta_background_image_url ] ).

To inject it, simply use the variabledata:

$( '.cta-parallax-section ' ).css( 'background', data );
195

Answer

Solution:

You can put some vars in head with this code:

add_action('wp_head', function(){ ?> <script type='text/javascript'> var bg_img = '<?php echo $bg_img; ?>'; </script> <?php });

And use bg_img var in your js code. But better way is using wp_localize_script function.

People are also looking for solutions to the problem: http - PHP Cross-Origin-Request blocked

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.