0

I've a function with on click method. After clicking an element with a class name, i want to do something. i called that function in document ready. and with jquery append method a dom element is being added with that class name. and i want to call that again to work that function again. but this time function is calling twice. please check below code for understanding.

function function_name() {
    $('.selector').on('click',function () {
        //do something
        console.log('a')
    });
}

$(document).ready(function(){
    function_name();
});

// after jquery append - a element with selector class is adding in dom.
// this call is inside a ajax call to bind that click with new dom element
function_name();

It's adding 'a' twice in console.

How to prevent this?

Santu Roy
  • 86
  • 1
  • 5
  • You are calling it twice ! – brk Mar 28 '20 at 10:08
  • i know. but 2nd call is after ajax succes.. what about a new dom element with selector class added with ajax. how to bind that function with newly added element? – Santu Roy Mar 28 '20 at 10:16
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Mar 28 '20 at 10:44
  • *what about a new dom element with selector class added with ajax. how to bind that function with newly added element* - use event delegation or bind to the new element directly (eg using `newElement.AppendTo(destination).on("click"...`) – freedomn-m Mar 28 '20 at 10:45
  • event delegation example: `$(document).on("click", ".selector", function() {...` – freedomn-m Mar 28 '20 at 10:53

1 Answers1

0

You should remove the one of your calls to the function_name() because this are calling this method twice.

The first time is called on your last statement of function_name().

// after jquery append - a element with selector class is adding in dom
function_name();


The second time is called when the document is loaded.

$(document).ready(function(){
    function_name();
});
Alexis Pavlidis
  • 1,080
  • 1
  • 11
  • 21
  • last function call is after a new dom element with selector class added by ajax/ jquery append to bind that click. that function call inside a ajax call. i know i called twice. but 2nd call is after ajax succes.. what about a new dom element with selector class added with ajax. how to bind that function with newly added element? – Santu Roy Mar 28 '20 at 10:12
  • You have to bind a click event on an element only once. – Alexis Pavlidis Mar 28 '20 at 10:18