Question

I am making a wordpress theme at the moment and to keep up with current trends I adding options to the theme customizer.

One of the options I've created is a background image uploader, the image uploads and even inserts to my site - however I'm using jQuery to make these changes appear in realtime and I've got a bit stuck.

Here is my JS for the image uploader to work in real time:

// BACKGROUND IMAGE
wp.customize( 'front_page_background_image', function( value ) {
    value.bind( function( to ) {
        $( '#banner' ).attr( 'style', function() {
            return 'background-image' : to ;});
    } );
});

What this does however is just return the following html:

<section id="banner" style="background-image"></section>

What I can't figure out is how to get the url of my image in the 'style' parameter. I knw that I can call the url using code like this:

// BACKGROUND IMAGE
wp.customize( 'front_page_background_image', function( value ) {
    value.bind( function( to ) {
        $( '#banner' ).html( to );
    } );
});

This will output

<section id="banner">[URL OF MY UPLOADED IMAGE]</section>

So I know it's possible to get the url, I just can't get it in the right place. What I need it to say is

<section id="banner" style="background-image:url=([URL OF MY UPLOADED IMAGE]);"></section>
Was it helpful?

Solution

Wrap the url with "url()". Note that using $.attr will cause existing styles to be lost. In the following example, the existing border is lost http://jsfiddle.net/mendesjuan/s9KTp/1/

$('#banner').attr('style', 'background-image:url(' +to+ ')');

You should use $.css instead of $.attr so that you don't have to worry about overwriting existing styles. See http://jsfiddle.net/mendesjuan/s9KTp/2/

$('#banner').css('background-image', "url("+ to +")");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top