The Problem:

You are developing something using the jquery API and you have attached an event handler method like .click() to an element, either by using .bind() or directly using the corresponding  API method of the event for example  .click(). When you click on the element you find as if the body of the event handler getting called twice. The bound event gets fired twice.

Sample Code:

or

Sample Code Output:

When you click on the element having the class button, the alert box appears twice or many times.

The Cause:

One of the reason I have experienced is, the element has been attached the event handler twice or many times (if the event fires many times) in the code. Probably you are creating the element dynamically. So each time you click on the element , the event handler fires each time it has been bound to the element.

The Solution:

Find out the duplicate places where you have attached the same event handler to the same element and remove them. If they are necessary and removing them is not an option for example if you are creating the elements dynamically or you can’t find where and how this duplication occurs then first unbind the handler and then rebind again, so that previously bound handler will get cancelled. Below is the example code:

or

Some also suggest using .stopPropagation() to use as a solution for this problem, but if the above mentioned problem is exact what you are having (while creating elements dynamically) , then .stopPropagation() may not work . I will explain in a later post where the jQuery API method .stopPropagation() is useful and how to use it.