Thao Nguyen
Thao Nguyen

Reputation: 901

Background setting: Javascript

I'm having trouble resizing a certain image to the dimensions of a container I have, when I set the image as a background.

#container {
    position: relative;
    height: 400px;
    width: 600px;
    left: 15%;
    border: 1px solid black;
    margin: 0;
    background-repeat: no-repeat;
}
<script language="JavaScript">
  function option1() {
    background="url('image.png')";
    document.getElementById('container').style.backgroundImage = background;
  }
</script>
.
.
.
.
<a href="#" id="b1" onclick ='option1()'>x</a>

I'm basically trying to make my links (which are x) change the background of the container as I click on them. The image are all have different sizes and I'm trying to find a way to change or resize the images to fit the container as I'm calling the function. I couldn't find anything so I gave up and just manually resize each image to the container size in an image editor. Is there any other way around this? I'm kind of new to Javascript and I tried looking at other code but it just throws me in loops sometimes.

__________________________________________
|                                        |
|                                        |
|                                        |
|__________________________________x_x_x_|

Upvotes: 0

Views: 43

Answers (1)

Shmiddty
Shmiddty

Reputation: 13967

You can see it in action here: http://jsfiddle.net/Shmiddty/Akypk/

With the pertinent CSS being:

background-size:100% auto;

The image will fill the width of the container, and its height will scale in proportion.

Upvotes: 1

Related Questions