-1

My slider output which reads the value given/updated by user using oninput event handler does not update correctly when I call using

slider.oninput = updateGridRange();

syntax with parenthesis, rather it gives me the same default value of 16x16. However the code works great without that bug when I call using

slider.oninput = updateGridRange; 

What is the difference in JavaScript when I call a function with no parameters defined functionExample() and functionExample without parentheses? Why is there a bug created in my code when this situation happens?

function createSlider() {
  const slider = document.createElement('input');
  slider.setAttribute('type', 'range');
  slider.setAttribute('min', '1');
  slider.setAttribute('max', '100');
  slider.setAttribute('value', '16');
  document.querySelector('div.slider-container').appendChild(slider);

  const sliderText = document.createElement('div');
  sliderText.classList.add('slider-text');
  document.querySelector('div.slider-container').insertBefore(sliderText, document.querySelector('div.slider-container').firstChild);
  
  sliderText.textContent = `${slider.value} x ${slider.value}`;
  slider.oninput = updateGridRange; //updateGridRange() causes bug
}

function updateGridRange() {
  document.querySelector('div.slider-container div.slider-text').textContent = `${document.querySelector('input').value} x ${document.querySelector('input').value}`;
}

Pictures of Slider

Bug

Good

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Please visit [help], take [tour] to see what and [ask]. Do some research, ***[search for related topics on SO](https://www.google.com/search?q=funtion+with+or+without+parenthesis+site%3Astackoverflow.com);*** if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jan 17 '22 at 19:56

2 Answers2

-1

updateGridRange is the function itself, and that's what you need to pass.

updateGridRange() is the result of calling updateGridRange, that is, it is whatever value is returned by calling updateGridRange.

Since you don't have a return value for the updateGridRange function, updateGridRange() is really just the same thing as undefined.

kshetline
  • 12,547
  • 4
  • 37
  • 73
-1

When doing

slider.oninput = updateGridRange;

you are assigning the function in the variable named updateGridRange, and it will be called later (a callback).

You only want it to fire when slider.oninput event happens, so you don't want to call the function immediately. Putting parenthesis on the end of a variable that holds a function will invoke it immediately, which is why you get bad behavior.

Dan Oswalt
  • 2,201
  • 2
  • 14
  • 24