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?

mheavers
  • 29,530
  • 58
  • 194
  • 315
  • 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. – NewToJS Jan 26 '18 at 00:10
  • can you provide an example of what you want to do. – Firas Omrane Jan 26 '18 at 00:29

1 Answers1

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:

esengineer
  • 9,514
  • 7
  • 45
  • 69