Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help to generate three blocks using loop

Following 3 block of code, want to generate using loop/array to make short code.I know use of loop is not a big thing, but for me its difficult to change counter with variable "openFile", I want counter increment with variable "openFile" like openFile1, openFile2 and openFile3 with each iteration of loop.

$(function() {

            var openFile1 = function(event) {
        var input = event.target;
        var reader = new FileReader();
        reader.onload = function(){
          var dataURL = reader.result;
          var output = document.getElementById('img1');
          output.src = dataURL;
        };
        reader.readAsDataURL(input.files[0]);
      };



      var openFile2 = function(event) {
        var input = event.target;
        var reader = new FileReader();
        reader.onload = function(){
          var dataURL = reader.result;
          var output = document.getElementById('img2');
          output.src = dataURL;
        };
        reader.readAsDataURL(input.files[0]);
      };

      var openFile3 = function(event) {
        var input = event.target;
        var reader = new FileReader();
        reader.onload = function(){
          var dataURL = reader.result;
          var output = document.getElementById('img3');
          output.src = dataURL;
        };
        reader.readAsDataURL(input.files[0]);
      };


       });
like image 580
dev Avatar asked Dec 06 '22 12:12

dev


1 Answers

Just create a function that takes count as arg and return a function that takes just event as arg. due to closure, the value of 'count' given when calling openFile with a given value of count will be used for the inner function.

  var openFileFunc = function(count) {
    return
        function(event) {
        var input = event.target;
        var reader = new FileReader();
        reader.onload = function(){
          var dataURL = reader.result;
          var output = document.getElementById('img'+(count+1));
          output.src = dataURL;
        };
        reader.readAsDataURL(input.files[count]);
      };
    }

Now you can get the three functions equivalent to what you did by calling a map like this:

var functions = [1,2,3].map(openFileFunc)

Each function in this array is the same as what you had.

like image 105
Binod Pant Avatar answered Dec 23 '22 11:12

Binod Pant