Konstantin Dinev
Konstantin Dinev

Reputation: 34905

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.

Upvotes: 5

Views: 7304

Answers (3)

stuartb
stuartb

Reputation: 364

Maybe add a css class for each background image then use:

$('html').attr('class', 'image4');

...to change the background image.

Upvotes: 1

Nenad
Nenad

Reputation: 26687

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

Upvotes: 6

Adil
Adil

Reputation: 148150

You need to give path without ~

url("/Content/images/image1.jpg")

Upvotes: 5

Related Questions