4

I want to have different background images for different conditions (JS,HTML,CSS). For E.g: if(n=1),then image 1 else if(n=2),then image 2 etc.

1
  • Have you tried to do this? Could you show us your code. Commented May 3, 2014 at 8:14

4 Answers 4

3

Try creating a Css class ..After that you can set it to your control from javascript..

document.getElementById("MyControl").className = "MyClass";

In the css class MyClass you can set the background image..You can create another css class with different background image and set it according to the conditions..

Sign up to request clarification or add additional context in comments.

Comments

1

It should be pretty easy in jQuery.

if(n == 1){
     $('your_image_element').css('background-image','url(your_first_img_path)') ;
}else if(n ==2){
      // second image...
}

Comments

1

Once you have picked the object you are manipulating, you can set its css properties directly from the script. E.g for the background image change on the body element:

var object = document.body;
object.style.backgroundImage="url('new_image.jpg')";

Comments

1

One way is to use script to dynamically change a CSS rule, e.g.

var image;

if ( /*some condition */ ) {
  image = 'a.png';
}  else {
  image = 'b.png';
}

document.write('<style type="text/css">.someClass {background-image:url("' + image + '");}<\/style>');

Of course there are more sophisticated ways to modify the rule, the above is just a basic method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.