agon024 agon024 - 1 year ago 99
jQuery Question

Randomly set background image

So I want to randomly set a background-image on an element.

Here is what I am trying:

<div id="headImg"></div>


$(document).ready(function() {

var images = ['bg.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg', 'bg6.jpg', 'bg7.jpg', 'bg8.jpg'];

$('#headImg').css( 'background-image', 'url(<?php echo get_template_directory_uri(); ?>/assets/images/' + images[Math.floor(Math.random() * images.length)] + ')' );



I am obviously doing something wrong since I cant get it to work.

This is also WordPress. So if I set and inline background image like this it works:

style="background-image: url(<?php echo get_template_directory_uri(); ?>/assets/images/bg.jpg);"

But I want to use jQuery to randomly set the background image inline. Is this even possible.

Any help is greatly appreciated.

Answer Source

The reason this code fails is because <?php echo get_template_directory_uri(); ?> can only be evaluated when the page is requested from the server. (PHP is a server side language.)

Hence, this line accomplishes nothing when dynamically generated with jQuery:

 $('#headImg').css( 'background-image', 'url(<?php echo get_template_directory_uri(); ?>/assets/images/' + images[Math.floor(Math.random() * images.length)] + ')' );

If, however, you replaced <?php echo get_template_directory_uri(); ?> with the return value of get_template_directory_uri();, to form this:

$('#headImg').css( 'background-image', 'url((return value here)/assets/images/' + images[Math.floor(Math.random() * images.length)] + ')' );

Your code would run properly.


As you can see from the comments below my post, people said--rightly so--that in certain cases, his code would've worked.

However, code like that only works if the jQuery is in the file being requested. However, in this case, the jQuery was not in the same file.

... That is why he had to remove the offending php tag.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download