'addEventListener' with two functions at the same time is not working

Viewed 58

I've added two event listeners to a range element and I want to update its value while it's modified... It doesn't update if I add two functions within one in the addEventListener method, but I can do it if they are separated.

const input = document.getElementById('blur');
const span = document.getElementById('blur-value');

function updateBlur() {
  const suffix = input.dataset.sizing || '';
  document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}

function updateSpan() {
  span.innerText = input.value;
}

//This does not work
input.addEventListener('mousemove', ()=>{
  updateBlur();
  updateSpan();
});

//This is the workaround
/*
input.addEventListener('mousemove',updateBlur);
input.addEventListener('mousemove',updateSpan);
*/
:root {
  --blur: 10px;
}

img {
  filter: blur(var(--blur));
}
<div>
  <label for="blur">Blur:</label>
  <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">
  <span id="blur-value">Value</span>
</div>
<img src="https://source.unsplash.com/7bwQXzbF6KE/" width=400px heigh=400px>

1 Answers

The problem was with the this reference, when you are calling from a event callback function, it loosing the this reference. Here is an updated function used, that can solve this issue.

function updateBlur() {
  const suffix = input.dataset.sizing || '';
  // this reference getting lost when you are calling from a callback function instead of binding in the event.
   
  document.documentElement.style.setProperty(`--${input.name}`, input.value + suffix);
}

const input = document.getElementById('blur');
const span = document.getElementById('blur-value');

function updateBlur() {
  const suffix = input.dataset.sizing || '';
  // this reference getting lost when you are calling from a callback function instead of binding in the event.
   
  document.documentElement.style.setProperty(`--${input.name}`, input.value + suffix);
}

function updateSpan() {
  span.innerText = input.value;
}

//This does not work
input.addEventListener('mousemove', ()=>{
  updateBlur();
  updateSpan();
});

//This is the workaround
/*
input.addEventListener('mousemove',updateBlur);
input.addEventListener('mousemove',updateSpan);
*/
:root {
  --blur: 10px;
}

img {
  filter: blur(var(--blur));
}
<div>
  <label for="blur">Blur:</label>
  <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">
  <span id="blur-value">Value</span>
</div>
<img src="https://source.unsplash.com/7bwQXzbF6KE/" width=400px heigh=400px>

Related