2

This is my code :

var myinp = document.querySelector(".myinp");
var store = document.querySelector(".store");

myinp.addEventListener("input", function() {update(store);}, false);

function update(elem) {
  console.log('Executed');
  elem.style.left= this.value + "%";
  if(this.value>0) {
    elem.textContent= this.value;
  } else {
    elem.textContent= null;
  }
}

The console just shows one Executed and even then the textContent does not change.

EDIT

This version of code works:

myinp.addEventListener("input", update, false);

function update() {
  thumb.style.left= this.value + "%";
  if(this.value>0) {
    thumb.textContent= this.value;
  } else {
    thumb.textContent= null;
  }
}

When I am not passing any parameters why does this refer to the element and not window just like in first case?.

SanJeet Singh
  • 1,211
  • 2
  • 12
  • 23

1 Answers1

3

The problem is that update function is executed in global context (window). If you want this to be an input instance you need to provide context explicitly:

myinp.addEventListener("input", function() {
  update.call(this, store);
}, false);

Remember that execution context depends on the way you invoke the function. In your case update is implicitly bound to the global object so calling it like update() will always have this being window.

dfsq
  • 182,609
  • 24
  • 222
  • 242
  • Hello @dfsq, can you tell us what `input` event is? – Marcos Pérez Gude Mar 10 '16 at 08:53
  • @dfsq Your suggestion worked! Thanks :) How does this work when I don't pass any parameter? I am updating the question to add another version of same function but without any parameters. I need to know to have a better understanding of JavaScript. – SanJeet Singh Mar 10 '16 at 08:57
  • @dfsq I'd also link to something explaining how `this` works in detail, like: http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Nickolay Mar 10 '16 at 08:57
  • 1
    @SanJeetSingh If you don't want to pass parameters you could simple do `myinp.addEventListener("input", update, false);` – dfsq Mar 10 '16 at 08:58
  • @dfsq When I am not passing any parameters why does `this` refer to the element and not window just like in first case? – SanJeet Singh Mar 10 '16 at 09:01
  • 2
    @SanJeetSingh Because if the function used as event handler `this` is set to the HTMLElement event attached to. Take a look at the doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_a_DOM_event_handler – dfsq Mar 10 '16 at 09:16