image-compare icon indicating copy to clipboard operation
image-compare copied to clipboard

Allow to specify a starting position for the slider

Open mably opened this issue 1 year ago • 3 comments

Everything is in the title 😉

mably avatar May 06 '24 10:05 mably

Ok, here is a small piece of code that seems to work:

var range_input = element.shadowRoot.querySelector('input');
if (range_input) {
  range_input.value = settings.image_compare.options.starting_position;
  range_input.dispatchEvent(new Event('change'));
}

Is it the right way to do it?

mably avatar May 06 '24 12:05 mably

Hey @mably,

This is a good idea for a feature!

The code you have seems like a good way to set the starting position from outside of the web component. 👍 (Assuming settings.image_compare.options.starting_position is always defined.)

I'm pretty busy with client work at the moment, but if I have some time in the future, I'll try to add this as a built-in feature of the web component. (You're also welcome to open a PR if you're interested. 🙂)

Paul-Hebert avatar May 06 '24 15:05 Paul-Hebert

For your information, I have implemented this solution in my new Drupal module : https://www.drupal.org/project/image_compare

I guess it could be easily integrated into the native library.

I just added a custom attribute start to the image-compare element like this:

<image-compare id="image-compare-slider" start="40" ... 

And then execute the following code once page is loaded:

once('image_compare', 'image-compare', context).forEach(function (element) {
  var range_input = element.shadowRoot.querySelector('input');
  if (range_input) {
    range_input.id = element.id + '_input';
    range_input.parentElement.setAttribute('for', range_input.id);
    range_input.value = element.getAttribute('start');
    range_input.dispatchEvent(new Event('change'));
  }
});

As you can see, we also added an id attribute to the image-compare element be able to link the input element and its label for accessibility reason.

mably avatar May 06 '24 18:05 mably