1

I'm not sure whether it's possible or not in my way. But I need it.

I have a css rule to define home page background image in style.css. I would like to randomly select an image from a directory. Images names are like main-bg-*.jpg (i.e. main-bg-1.jpg, main-bg-2.jpg).

CSS

#background-div {
padding: 0;
margin: 0;
color: #000;
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
z-index: -1;
background-image: url('../Images/Backgrounds/home-page-bg-1.jpg');
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-color: #464646;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}

HTML

<body>
   <div id="background-div"></div>
   -------
   -------
</body>

I want to generate a number between 1 to 10 in controller method, then pass it to the css rule.

How can i do it?

If there is any other convenient way, please let me know.

Sorry if this is a silly question.

Thank you.

3
  • Why not doing it from JS. You can access background DOM element and update with random number for images Commented Jan 21, 2015 at 6:22
  • @qamar, If it can be done in js, i have no problem. Would you please show an example? Commented Jan 21, 2015 at 6:25
  • can you paste your css for background image so that I can work out an example for you :) Commented Jan 21, 2015 at 6:28

3 Answers 3

2

May be you can do something like following to set background image from JS.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(your image url)';
Sign up to request clarification or add additional context in comments.

Comments

2

JS:

var img = 'main-bg-'+ Math.floor((Math.random() * 10) + 1)+'.jpg';
 document.getElementById('elementid').style.backgroundImage = url(img);

Comments

0

One way you could do this in C# and CSS is to add a class to the div aswell as using the ID:

<body>
   <div id="background-div" class="background1"></div>
   -------
   -------
</body>

and setting up the 10 classes in CSS:

.background1 { background-image: url('../Images/Backgrounds/home-page-bg-1.jpg'); } 

...

.background10 { background-image: url('../Images/Backgrounds/home-page-bg-10.jpg'); }

I know you already selected an answer, just suggesting as a way to do what you requested without the requirement for javascript

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.