-1

I have two click functions in a file,

$('#login').click(function() {
  // something
  // also adding the logout part
  $('#navigation').append('<li id="logout"><a href="#" >Logout</a></li>');
});

$('#logout').click(function() {
  // something
});

When I load the page first time, do a login and then directly do logout, the $('#logout').click() doesn't work. Now if I do a page refresh then it starts working. Is this not the correct way to provide click functions. Or is it that, as the #logout is not created at the beginning the $('#logout').click() is not loaded?

Nav
  • 39
  • 5
  • possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – Tieson T. Aug 24 '14 at 06:14

2 Answers2

0

You need to use event delegation:

$('#navigation').on('click','#logout',function() {
  // something
});

or attach the event after appending the DOM:

$('#login').click(function() {
 // something
 // also adding the logout part
 $('#navigation').append('<li id="logout"><a href="#" >Logout</a></li>');

 $('#navigation').on('click','#logout',function() {
  // something
 });
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

maybe for one of this reasons:

1-maybe you used a false class or id (maybe)


2-When you login maybe you are using ajax and adding some new element to your page, if this is true you can't use common jquery functions, You should Attach an event handler function for one or more events to the selected elements by .on()

Two ways of using .on():

    function logout() {
      alert( "clicked" );
   }
   $( "#logout" ).on( "click", logout);

other way:

    $( "body" ).on( "click", "#logout", function() {
      alert("logout");
    });
Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61