Keyfer Mathewson
Keyfer Mathewson

Reputation: 1075

PHP + JQuery setting background images

I've got a php variable, which i pass to a jquery script, which I want to set the background of a certain div. nothing seems to work though.

here's the code:

<?php $post_thumbnail_id = get_post_thumbnail_id(); ?>
<?php $post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id ); ?>
<script type="text/javascript">
  $(document).ready(function(){
      $("#event-sub-hero").css('background', 'url("<?php echo $post_thumbnail_url ?>")');
    });
</script>

<!-- SUBPAGE HEADER -->
  <div id="event-sub-hero">
    <div class="container">
      <div class="sub-hero-text col-lg-6 col-lg-offset-3 col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3 col-xs-12">
        <h2><?php the_title(); ?></h2>
      </div> <!-- end sub-hero-text -->
    </div> <!-- end container -->
  </div> <!-- end sub-hero -->

<!-- END SUBPAGE HEADER -->

This is the code it spits out:

  $(document).ready(function(){
      $("#event-sub-hero").css('background', 'url("http://localhost:8888/babble/wp-content/uploads/2013/10/madmen-night.jpg")');
    });

Upvotes: 0

Views: 189

Answers (3)

TimDC
TimDC

Reputation: 121

Don't use the double quotes, you shouldn't need them, and as someone else mentioned, using 'background-image' is more correct when you are only setting the background image.

Upvotes: 0

okawei
okawei

Reputation: 1527

Have you tried just setting the background of that element with straight up CSS? Maybe the element isn't appearing how you would expect. Also, I'd use background-image as well.

Upvotes: 0

BadHorsie
BadHorsie

Reputation: 14544

Try background-image instead of CSS background

Upvotes: 1

Related Questions