Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic background-image in MVC 4 application

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.

like image 740
Konstantin Dinev Avatar asked Oct 09 '12 21:10

Konstantin Dinev


1 Answers

your background array is composed in a wrong way. In .cshtml file it should look like this:

var background = ['@Url.Content("~/Content/images/image1.jpg")',
    '@Url.Content("~/Content/images/image2.jpg")',
    '@Url.Content("~/Content/images/image3.jpg")',
    '@Url.Content("~/Content/images/image4.jpg")',
    '@Url.Content("~/Content/images/image5.jpg")'];

This way Url.Content(...) function will resolve path into correct string. Check what is rendered on the page in browser.

Ahh, and then you can wrap in with 'url()' for css.

$('html').css('background-image', 'url(' + background[index] + ')')
like image 165
Nenad Avatar answered Oct 06 '22 01:10

Nenad