2

I'm practicing my JS skills (I'm new at it). I'm trying to get the specific element that triggered the event and display it in a span element. But I don't know what I'm doing wrong, when I click the button nothing happens.

This is for a calculator program that I'm doing but using module pattern I think it's called.

var Calculator = {
  init: function(){
    var button = document.querySelectorAll("[class^='button']");
    button.onclick = this.writeEvent;
  },
  write: function (element){
    document.getElementById("display").innerHTML = element;
  },
  writeEvent: function(event){
    write(target.event)
  }
}

Calculator.init();
2
  • 2
    Its event.target, please check the console next time before asking here ;) Commented Nov 3, 2017 at 23:22
  • Also, button.onclick won't work because button is a NodeList not an Element. Commented Nov 3, 2017 at 23:36

1 Answer 1

1

There are several problems with the posted code.


    var button = document.querySelectorAll("[class^='button']");
    button.onclick = this.writeEvent;

The result of querySelectorAll is a NodeList. Assigning to its onclick property will not achieve what you want. You want to assign to the onclick property of each individual node.

But actually that's not so simple, we'll need to come back to this.


  writeEvent: function(event){
    write(target.event)
  }

One problem here is that target is undefined. Surely you meant event.target.

Another problem is that write is also undefined. Perhaps you meant this.write, but that won't actually work well. The problem is that when writeEvent is called from a click event, it won't be called on the object, so this will not be bound to the calculator object, and the this.write call will raise an exception.

There's a way to overcome this, by binding the onclick handler function to the object when setting it.


Putting the above together:

var Calculator = {
  init: function() {
    var nodeList = document.querySelectorAll("[class^='button']");
    var callback = this.writeEvent.bind(this);
    nodeList.forEach(item => item.onclick = callback);
  },
  write: function(element) {
    document.getElementById("display").innerHTML = element;
  },
  writeEvent: function(event) {
    this.write(event.target);
  }
}

Calculator.init();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.