3

I am using the object-fit and object-position css properties to control the placement of an image in css. I want to programmatically set that position with javascript. I tried:

const panPos = 50;
document.querySelector('.image').style.objectPosition = `${panPos}% 0%`;

and nothing happens.

I can console log element.style and I see an objectPosition property, but setting it seems to have no effect.

Please note I am not talking about the position property (absolute, relative, etc).

I can also set this property with jquery using:

$('.image').css({
      'object-position': `${panPos}% 50%`  
    });

but I want to avoid jQuery. Any ideas?

2
  • have you tried using document.querySelector('.image')[0]? Also if you want this to function for multiple elements then you will need to iterate through the node collection and maybe using document.querySelectorAll('.image') would be better for multiple elements. Commented Jan 26, 2018 at 0:10
  • can you provide an example of what you want to do. Commented Jan 26, 2018 at 0:29

1 Answer 1

2

You need to set object-fit to none as well. They are used together, otherwise, object-position gets ignored. So:

const panPos = 50;
document.querySelector('.image').style.objectFit = 'none';
document.querySelector('.image').style.objectPosition = `${panPos}% 0%`;

For more info, refer to:

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

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.