-2

I'm still trying to get back from a nested callback function inner functions return value but already I ran out of ideas.

Here is the code:

function addListener() {
  var imgs = document.getElementsByClassName('img');
  var ids = document.getElementsByClassName('item');
  for (let i = 0; i < imgs.length; i++) {
    let img = imgs[i];
    img.addEventListener('click', function() {
      var card_1 = function getId() {
        var Id = ids[i].id;
        return Id;
      };
      img.style.opacity = "1.0";
      window.setTimeout(function() {
        img.style.opacity = "0.0"
      }, 2000)
    });
  }
}

Thanks in advance!

user7637745
  • 965
  • 2
  • 14
  • 27
  • 1
    What specific error or issue are you having with this code? Is the problem the image opacity is NOT changing but should? Or are you trying to return something here? – RoboBear Jul 01 '18 at 18:28
  • You are selecting ids and imgs by class name, are you sure about it? – dhaker Jul 01 '18 at 18:29
  • 1
    You've defined a variable called `card_1` but never used it. Is that an oversight or is it part of the question? – Ray Toal Jul 01 '18 at 18:29
  • Read about closures – dhaker Jul 01 '18 at 18:31
  • There are images inside divs and I would like to get the divs id which contains the image when I clicked on it. – Gergely Kudó Jul 01 '18 at 18:33
  • Possible duplicate of [addEventListener using for loop and passing values](https://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values) – t.niese Jul 01 '18 at 18:40
  • [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – t.niese Jul 01 '18 at 18:40
  • 1
    This question is hard to understand with code that doesn't make too much sense. Why are you declaring a function and never calling it? What are you hoping to do? When do you want the id of the clicked element? – Robert Mennell Jul 01 '18 at 18:54

1 Answers1

0

Most likely you need to use a callback, you cannot return a value from this function, because the work the function does is asynchronous:

function addListener(cb) {
  var imgs = document.getElementsByClassName('img');
  var ids = document.getElementsByClassName('item');
  for (let i = 0; i < imgs.length; i++) {
    let img = imgs[i];
    var Id = ids[i].id;
    img.addEventListener('click', function() {
        cb(null,Id);         // use an error-first callback
      img.style.opacity = "1.0";
      window.setTimeout(function() {
        img.style.opacity = "0.0"
      }, 2000)
    });
  }
}

call the function like so:

addListener(function(err,id){

});
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817