mdibb.co.uk

Irreguarly rambling about web development and technology

Change the Background-Position with Javascript

I came across a little quirk today when trying to change the position of a background-image with javascript. I tried and I tried but I just couldn’t change the background image position with javascript.

Typically, you just use something like this to change an element’s style with javascript, where attribute is the CSS attribute you want to change (e.g. width, margin etc)

document.getElementById("blah").style.attribute = blah


However, for background-position (i.e. as CSS refers to it!) you need to change the attribute to be backgroundPosition - note the capital P and the missing hyphen! So now, to change the backgroung-position using javascript, I’d use something like this:

document.getElementById("blah").style.backgroundPosition = "10px 10px"

It turns out that the same goes for all of the hyphenated attributes too:

CSS Name Javascript Name
background-attachment backgroundAttachment
background-color backgroundColor
background-image backgroundImage
background-position backgroundPosition
background-repeat backgroundRepeat

Activity

One comment, leave your comment or trackback.
  1. Thanks for the tip! It really helped!

    I refer to the following:

    “However, for background-position (i.e. as CSS refers to it!) you need to change the attribute to be backgroundPosition - note the capital P and the missing hyphen! So now, to change the backgroung-position using javascript, I’d use something like this:

    document.getElementById(”blah”).style.backgroundPosition = “10px 10px”

    It turns out that the same goes for all of the hyphenated attributes too:”


Leave a Reply


Search

The archives run deep. Feel free to search older content using topic keywords.

Browse by Category