I am trying to select a random background image for my MVC application. Inside my _Layout.cshtml, I have the following code:
<script type="text/javascript"> var background = ['url("~/Content/images/image1.jpg")', 'url("~/Content/images/image2.jpg")', 'url("~/Content/images/image3.jpg")', 'url("~/Content/images/image4.jpg")', 'url("~/Content/images/image5.jpg")']; $(document).ready(function () { PickRandomBackground(); }); function PickRandomBackground() { var index = Math.floor(Math.random() * 5); $('html').css('background-image', background[index]) } </script>
What ultimately happens is that the image cannot be found. My site.css is located in the "Content" folder, and if I define the image as follows:
html { background-image: url("images/image1.jpg"); background-position:center; background-repeat: no-repeat; background-color: #e2e2e2; margin: 0; padding: 0; }
Then he finds it correctly, however, if I make the same definition inside my javascript ( .css('background-image', 'url("images/image1.jpg") ), it is not. I am running out of ideas, so please help me with this.
source share