I am using this function in NW.JS to get a file locations of images. I use that file location in the callback to modify a div background using .css() in jquery. My problem is that the script seems to remember the last div that it modified. When I try to use this to change the background of another div after previously having used it to change the background on a different div BOTH divs change their backgrounds. I guess I need to be able to get this script to know what button clicked it and to forget anything that another button asked it to do. As you can tell I am new to javascript. How can I do that?
function chooseFile(name, handleFile) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
for(var f of this.files){
console.log(f.name);
console.log(f.path);
handleFile(f.name, f.path);
}
}, false);
chooser.click();
}
chooseFile('#fileDialog', function(name, path){ ... /* do something with the file(s) */ });
In many cases, it’ll make sense to write your script so that it can react to new files:
const chooser = document.getElementById('fileDialog');
// Treat chooser as a stream of new files that can be added at any time
chooser.addEventListener("change", function (evt) {
for (const f of this.files) {
console.log(f.name);
console.log(f.path);
handleFile(f.name, f.path);
}
}, false);
// Then, when you want to prompt for a new file at any point in the future…
function promptForFiles() {
chooser.click();
}
When that’s not possible, you can instead have it hold a maximum of one handler at a time by assigning to the old but reliable onchange
property:
function chooseFile(name, handleFile) {
const chooser = document.querySelector(name);
chooser.onchange = function () {
for (const f of this.files) {
console.log(f.name);
console.log(f.path);
handleFile(f.name, f.path);
}
};
chooser.click();
}