Q:

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>

<script>

  $(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)] + ')' );

  });

</script>

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.

A:

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.
Edit:
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 that embeds php only works if the code is in the file being requested. (ie. It is inline code, rather than external code from different pages.) However, in this case, the jQuery was not in the same file ... That is why he had to remove the offending php tag.
In recap: 
This solution was necessary because the javascript was not in the requested .php file. Hence, the PHP tags were not evaluated. (PHP tags mean nothing in javascript files.)
If, however, the javascript would have been in the requested PHP file, it would've worked fine.

