Search code examples
jquerymodalpopup

jQuery: Have same event attached to multiple controls on same page


I have a form on which certain questions has special css class associated with them. Now on document.ready, I have $('.cssclassname').on where I get some data through ajax call and display that returned data in that class row.

One of the components returned is a button, clicking on which brings up jQuery ModalPopup and on getting data in my $('.cssclassname').on, I attach my ModalPopup event so that ModalPopup works correct through that button click.

Now problem I am facing is , sometimes, I can have 3-4 buttons on my page, every time I click on 1 button, the code to open modalpopup runs x no of times (where x is number of buttons). I think the problem is as modalpopup has same class and I am attaching same events x number of times due to x numbers of buttons.

Is their any way to solve this problem where I only attach particular event function once per page load.

I am bit confused explaining this question but let me know anyone can help me in this or needs any more clarification.

Thanks


Solution

  • As i understand it, you have two options:

    • unbind event before rebind it using .off()(weird)
    • use delegation with .on():

      $(document).on("click", ".className", function(){});