0

I have a jQuery statement adding new html code to an element, like this:

$(".welcome").removeClass("guest").addClass("user")
  .text("")
  .append("Welcome "+$('#username').val()+"! <a href=\"/admin/\" id=\"adminlink\">Control Panel</a> &mdash; ")
  .append(
    $("<a href=\"login.php?logout\" id=\"logoutlink\">Logout</a>").click(function(event)
        {
             $("#logoutlink").click();
        })
).fadeIn("slow");

I've used the append() method in order to allow jQuery to handle the click event on the tag, but it's not working for some reason. I've read this question, but I can't figure out why this isn't working.

Thanks.

Community
  • 1
  • 1
DavideR
  • 540
  • 3
  • 18
  • 3
    Your click handler just calls the click handler again. – Barmar May 21 '14 at 17:48
  • 1
    Why not use event delegation as in http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar May 21 '14 at 17:49
  • Are you looking at something like this? http://jsfiddle.net/7pdFF/ – karthikr May 21 '14 at 17:51
  • @Barmar I know that it calls the click handler again, I want it to do so because I have previously declared that handle. – DavideR May 21 '14 at 17:52
  • @DavideR -- Then create a function that both handlers use, don't trigger a click event on a different element to do something, that could get ugly real quickl. – tymeJV May 21 '14 at 17:53
  • How could you have previously declared that handler? You're declaring it right there. You're creating an infinite recursion. – Barmar May 21 '14 at 17:55

1 Answers1

1

In order to bind a click handler to an element that is appended to the DOM, you need to use event delegation, like this:

$(".welcome").removeClass("guest").addClass("user")
  .text("")
  .append("Welcome "+$('#username').val()+"! <a href=\"/admin/\" id=\"adminlink\">Control Panel</a> &mdash; ")
  .append(
    $("<a href=\"login.php?logout\" id=\"logoutlink\">Logout</a>"))
).fadeIn("slow");

$(document).on("click", "#logoutlink", function(){

    alert("do something");
});

For more information you can go here, and look at the section titled, "Direct and delegated events."

MDiesel
  • 2,619
  • 10
  • 14