0

I'm trying to select an DOM element and store it in an object and then later accessing it by a click event.

this._elements.convertButton.click(function(e) {
    _this.convertButtonClicked.notify();
});

If I initially select the element using JQuery all is fine

{ convertButton: $("#convert") }

However if I don't use JQuery the click does not work

{ convertButton: document.getElementById("convert") }

While using Jquery is not an major issue I was simply looking for clarification on how to make it work using pure javascript and why the click is fine on the JQuery object and not on the ordinary object.

1
  • The click method of a jQuery object (the return from $('convert')) is quite different from the click method of a DOM object. Commented Nov 29, 2016 at 0:03

2 Answers 2

2

Need to use addEventListener:

this._elements.convertButton.addEventListener("click",function(e) {
    _this.convertButtonClicked.notify();
});
Sign up to request clarification or add additional context in comments.

Comments

1

Two solutions:

1. jQuery:

$(this._elements.convertButton).click(function(e) {
    _this.convertButtonClicked.notify();
});

2. Plain Javascript:

this._elements.convertButton.addEventListener('click', function(e) {
    _this.convertButtonClicked.notify();
}

Explanation: What's probably happening is this._elements.convertButton is an Element instance, not a jQuery object, so the jQuery .click() method is unavailable. You can either use the standard .addEventListener('click', ... as an alternative, or wrap this._elements.convertButton in a jQuery object by using $(this._elements.convertButton).

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.