I am trying to pick 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 ends up happening is that the image cannot be found. My site.css is located in the Content folder and if I define the image the following way there:
html {
background-image: url("images/image1.jpg");
background-position:center;
background-repeat: no-repeat;
background-color: #e2e2e2;
margin: 0;
padding: 0;
}
Then it correctly finds it, however if I do the same definition inside my javascript (.css('background-image', 'url("images/image1.jpg")) it doesn’t. I am running out of ideas so please help me with this.
You need to give path without
~