Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Igor Yamshchykov
Igor Yamshchykov
24,397 Points

jQuery click event bind multiple times ?

I have modal window that is opening on click on some element in the grid

$('#table tbody').on('click', '.btn-edit', editModal);

function editModal() {
    var modal = $('#editModal').modal('show');
    $('#saveButton').on('click', { modal: modal }, save)
}

function save(){
    //implementation here.
}

The problem is I can call this modal multiple times and in editModal the click event is binding more than one time, so then the save method fires multiple times.

I founded one solution for that, is to use

$('#saveButton').off('click').on('click', { modal: modal }, save)

but I think there should be a better way to handle this, could someone help me on that ?

1 Answer

You could/should take the binding of the click event on the #saveButton out of the editModal function. That way it only binds the event once, when the script is loaded (same as the binding at the top of your example).

Presumably the #saveButton is only visible when the modal is showing/visible, but it just has to already exist in the DOM before you bind an event to it.

Also, don't forget to use event.preventDefault within those functions if you're using a/hyperlink elements to fire the click events.

Igor Yamshchykov
Igor Yamshchykov
24,397 Points

Thanks, I have one more question regarding using binding outside the function. If I will take out my binding to the outside of the function is there some way to modify the parameters I pass to the event function from the local scope of editModal function? Or this is a bad approach to deal with such problems ?

You can pass data to the function you're binding and access it using the event object, as described in jQuery's on() documentation, second example.

Hope that helps!