2

Since I started structuring my JavaScript as a module pattern, some of my click events no longer work. Since other parts of my JavaScript add HTML to the DOM, I need to use $('body').on('click') for a button.

This is what my module currently looks like:

var s,
MyApp = {    

  settings: {
    fooButton: $(".foo-button"),
    barButton: $(".bar-button")
  },    

  init: function() {
    s = this.settings;
    this.bindEvents();
  },    

  bindEvents: function() {
    // this works
    s.fooButton.on("click", function() {
      MyApp.clickButton("foo");
    });    

    // this does NOT work
    $('body').on('click', s.barButton, function (event) {
      MyApp.clickButton("bar");
    });
  },    

  clickButton: function(button) {
    console.log("You clicked " + button)
  }    

};

The first click event is working, the second isn't. How can I bind and event for an element that was created by JavaScript code?

2
  • try $('body').on('click', s.barButton.attr("id"), function (event){... instead. Commented May 2, 2016 at 20:06
  • Since you have a reference to the object that was created (ie, s.fooButton or s.barButton) there is no need to use $('body').on('click', 'selector', ...). You can simply use s.fooButton.on("click", function... Commented May 2, 2016 at 20:32

3 Answers 3

1

The second argument for your handler when the event is delegated is expected to be a string.

In your case it is a jQuery Object. That is the root cause your click event is not working.

Change

barButton: $(".bar-button")

to

barButton: ".bar-button"
Sign up to request clarification or add additional context in comments.

Comments

0

If you're creating the element in JS, you have to bind the event AFTER the element is created.

So put the binding event in a function, then call that function after your JS code has created the element. :)

Comments

0

When using .on() for event delegation, the second parameter has to be a string. Passing anything else won't work.

http://api.jquery.com/on/#on-events-selector-data

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.