Search code examples
jquerydynamically-generated-co

.on event firing on load instead of click


Ok guys im new to jquery and have been making considerable progress but this one has me stumped. i have a event handler I'm binding to a dynamically loaded div to handle clicks hovers etc however when i try to bind a custom function it fires it on load instead of when clicked.

function AddUser(){
       alert('Hi');
       if ($section !== 'addUser'){
           $section = 'addUser';        
       $('.userPanel').empty();
       $('.userPanel').load('pages/addUser.html');
       }
       else{return;}
    }

    $(document).on("click", "a.addUser", AddUser());

However if i define an event inside of the .on binding it works fine

        $(document).on("click", "a.addUser",function(){
        alert('Hi');
    });

I probably missed something elementary but this has had me frusterated all morning so any help would be appreciated.

Note: I realize that binding to document is generic and i should be binding to the one of my static parent divs it was just a change i made while testing.

Thanks In Advance.


Solution

  • Change:

    $(document).on("click", "a.addUser", AddUser());
    

    to

    $(document).on("click", "a.addUser", AddUser);
    

    By adding the parenthesis to AddUser you're effectively calling it at that point in your code.