Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background-image size in javascript

I have been attempting to put a repeating background image on a website, with the basic CSS

background-image: url('url_here');
background-attachment: fixed;
background-repeat: repeat;

however, id like to be able to change the size of the image im using on refresh, using javascript. CSS has the function

background-size: 300px;

but unfortunately the COM style object doesnt - see here for what it can do for backgrounds. This leaves me with one option: using an HTML image that repeats itself, that i can then edit with the COM style object.

So, boiled down, my question is: is there a way to repeat an HTML image that is NOT a background image? Any help is greatly appreciatted.

like image 231
pinkie Avatar asked Apr 02 '13 04:04

pinkie


People also ask

How do I change the size of an image in JavaScript?

Answer: Use the JavaScript width and height property You can use either width or height JavaScript property to proportionally increase and decrease the dimension of an image like zoom-in and zoom-out feature.

How do I make the background image fit my screen size?

Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.

How do I change the background image size in CSS?

The background-size property is used to set the background image size using CSS. Use height and width property to set the size of the background image.


3 Answers

Actually, you CAN affect the background size in javascript like so:

document.getElementById("el_id").style.backgroundSize = "100px 100px";

Check out this fiddle: http://jsfiddle.net/Lph2W/. The CSS sets the background image size to 200px X 200px, then the JS updates it to 100px X 100px.

like image 109
Rodney Golpe Avatar answered Nov 13 '22 00:11

Rodney Golpe


This worked for me and I hope this helps some one else.

var el = document.getElementById("notification");
el.style.background = 'url(images/Noti.png) no-repeat center center';
el.style.backgroundSize="100% 100%";

If you found this useful please don't forget to vote UP :)

like image 44
Kingsley Mitchell Avatar answered Nov 12 '22 23:11

Kingsley Mitchell


It appears that using:

style.backgroundSize = 300px;

in the place of:

style.background-size = 300px;

solves this issue, but I wanted to point out a shorthand version as well:

style.background = "url('url_here') repeat fixed /300px";

just remember to keep the background size on the end, as if its added in the middle it seems to break.

like image 1
Kae Cyphet Avatar answered Nov 12 '22 23:11

Kae Cyphet