I am trying to create a slider with javscript. I would like to have two functions - first of them, parseDom(), should be responsible for getting elements from DOM; the second one, configureRange(), should be responsible for setting range attributes, like min and max values. Both functions are called inside anonymous function, which is assigned to window.onload variable.
function parseDom() {
var main = document.getElementById('main');
main.classList.add('red');
// red class added - main selector is ok
var rangeContainer = main.querySelector('.range-container');
rangeContainer.classList.add('green');
// green class added - rangeContainer selector is ok
var rangeInput = rangeContainer.querySelector('.range-input');
rangeInput.classList.add('crosshair');
// crosshair class added - rangeInput selector is ok
}
function configureRange(){
rangeInput.classList.add('pointer');
rangeInput.setAttribute('min', '0');
}
window.onload = function(){
parseDom();
configureRange();
}
However, variables from parseDom() can't be accesed from configureRange(), because variables inside these functions are in different scopes. So my code inside configureRange() does not work. I could do all things in one function instead of two, but this would make code messy. How do I create a good modular solution?
Code is here: https://codepen.io/t411tocreate/pen/oeKwbW?editors=1111
The simplest thing is probably to pass
configureRangethe information it needs, by havingparseDomcall it:...or by having a controller function (
parseAndConfigure, whatever) that looks up the input and passes it to both functions.Side note: In terms of keeping functions small and ensuring the name is indicative of what it does (as seems to be your goal),
parseDomdoesn't parse anything, and it does more than just identify the relevant DOM elements (it also adds classes to them). Perhaps three functions:getDom,addClasses, andconfigureRangeor similar. Then:...or something like that.