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.