Dynamic background image in MVC 4 application

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.

+4
source share
3 answers

You need to specify the path without ~

 url("/Content/images/image1.jpg") 
+4
source

Your background array is not compiled correctly. In the .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")']; 

Thus, the Url.Content (...) function will resolve the path to the correct line. Check what is displayed on the page in the browser.

Ahh, and then you can enable it using 'url ()' for css.

 $('html').css('background-image', 'url(' + background[index] + ')') 
+6
source

Perhaps add a css class for each background image, then use:

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

... to change the background image.

+1
source

Source: https://habr.com/ru/post/1438762/


All Articles