makkusu
makkusu

Reputation: 858

Click Event inside of a jQuery Plugin on another element doesn't work

I found many articles about this topic on stackoverflow but no one gave me a solution on my exact problem.

I have a jQuery Plugin which works fine so far. In that plugin I add some new DIVs. Also I want to add a click event listener on these new DIVs. Like this:

(function ($) {
  $.fn.myFunc = function(options) {

    // Options + Defaults
    var settings = $.extend({
      // Some options in here
    }, options);

    var controls = "\
      <div class='controls'>\
        <button class='btn-add-text'>Add Text</button>\
      </div>\
    ";

    $('.btn-add-text').click(function() {
      alert("Test");
    });

    $(this).after(controls);

    return this;
  };
})(jQuery);

My first thought was, that it is not possible because the event listener was called before the new div is actually inside of the DOM, so it can't work. So I moved the .click(func... Block outside of the plugin code and put it inside of a document.ready function like so:

$(document).ready(function() {
  $('.btn-add-text').click(function() {
    alert("Test");
  });
});

This also won't work for me. Is there any solution for this problem?

Upvotes: 2

Views: 1504

Answers (2)

halkujabra
halkujabra

Reputation: 2942

To make it work on new DIVs you have to do something like -

$('.controls .btn-add-text').click(function() {
      alert("Test");
    });

If it doesn't work, then try disabling the cache and refresh.

Edit:

Overlooked something. Actually you are just registering the inner function(with 'options' parameter). You need to get it run to add the actual div element.

Your outer function is running because it is enclosed in () but the inner one is not.

Upvotes: 1

Entity Black
Entity Black

Reputation: 3491

Try to use more variables to store html (jquery) elements.

(function ($) {
  $.fn.myFunc = function(options) {

    // Options + Defaults
    var settings = $.extend({
      // Some options in here
    }, options);

    var button = $('<button class="btn-add-text">Add Text</button>');

    button.click(function() {
      alert("Test");
    });

    var controls = $('<div class="controls"></div>')
                   .append(button);

    $(this).after(controls);

    return this;
  };
})(jQuery);

You use $('.btn-add-text').click( ... ) and then you add this element to html with $(this).after(controls). So jquery selector function can't find this element in html, becouse it is not here.

Also your concept isn't correct, becouse you add event listener on all elements .btn-add-text every time you call myFunc which can overload client javascript. Add event listeners only to elements that you are currently creating.

Upvotes: 2

Related Questions