1

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.

5 Answers5

8

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
3
$(document).on("click", "a.addUser", AddUser);

or

$(document).on("click", "a.addUser", function(){
   AddUser();
 });
xkeshav
  • 53,360
  • 44
  • 177
  • 245
2

Just remove the parentheses from AddUser()

$(document).on("click", "a.addUser", AddUser);
Andreas
  • 21,535
  • 7
  • 47
  • 56
1

Change

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

to

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

Because AddUser() is self-invoked and executed after page load.

OR

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

because, function() { AddUser(); } is not self-invoked block and will execute everything within it when the event occurs.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

use function signature otherwise you will be invoking the function.. change it to

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

Demo

Baz1nga
  • 15,485
  • 3
  • 35
  • 61