-1

I have code which collects elements with class .colors

var colors = document.querySelectorAll('.colors');

And loop which assigns event to all that elements.

for (var i=0;i<colors.length;i++) {
    var color = colors[i];
    color.addEventListener('click', remember(color.getAttribute('id')), false);
}

How can I send parameter (in this sample- 'color.getAttribute('id')') to function (in this sample- 'remember') without her initiation?

function remember(color_value) {
  localStorage.setItem('color', color_value); }
Adamsky97
  • 43
  • 5
  • I don't think it's possible! – Pugazh Aug 09 '16 at 07:28
  • 1
    I don't think your question is explained enough. Are you trying to find "color"'s id without using ".getAttribute"? – NachoDawg Aug 09 '16 at 07:29
  • If you want to get the `id` of the DOM element clicked. You can get it in the `clickListener` anyway. You can get the `target` element of the listener and then do `getAttribute` – Vivek Pradhan Aug 09 '16 at 07:34
  • 1
    I trying to send color.getAttribute value as a parameter to function. The problem is browser interpreting code line with function name and brackets as inititation of function. But it isn't- brackets are used only for sending parameter. – Adamsky97 Aug 09 '16 at 07:36
  • 1
    @Adamsky97 : Yes, thats the desired behaviour. Try `color.addEventListener('click', function(){ remember(color.getAttribute('id')) }, false);` – Pugazh Aug 09 '16 at 07:37
  • Possible duplicate of [How can I pass a parameter to a setTimeout() callback?](http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) –  Aug 09 '16 at 07:43
  • @Pugazh this should be an answer, since it's... the answer. – moopet Aug 09 '16 at 07:44
  • @moopet : Thanks, I added it as an answer. – Pugazh Aug 09 '16 at 07:52

1 Answers1

2

Functional parameters can't be passed directly to event listener's. Instead instantiate a simple function and pass the parameter like below.

function remember(id) {
  console.log(id);
}

var colors = document.querySelectorAll('.colors');

for (var i = 0; i < colors.length; i++) {
  var color = colors[i];
  color.addEventListener('click', function() {
    remember(this.getAttribute('id'))
  }, false);
}
.colors {
  padding: 5px 10px;
  background-color: lightgreen;
}
<div id="div1" class="colors">Click Me - I'm Div 1</div>
<br>
<div id="div2id" class="colors">Click Me - I'm Div 2</div>
Pugazh
  • 9,453
  • 5
  • 33
  • 54
  • I believe `color` should be `this` in the callback function else it'll always be accessing the last element. – moopet Aug 09 '16 at 11:04