Lloyd Banks
Lloyd Banks

Reputation: 36648

Referencing AJAX loaded DIV IDs

I have a "command center" bar on my website that has a log in / log out button, a my account button, and a messages button. If the user is not logged in, the command center only displays the login button. If the user is logged in, the command center displays logout, my account, and messages buttons.

I use jQuery AJAX to refresh the command center when a user logs in or out. So when a user logs in, his / her info is posted to a php page and a callback function refreshes the command center. I have another jQuery AJAX function that when it senses a click on the logout button (only appears after a user logs in), it posts to a php page that logs the user out.

Since the log out button is loaded via AJAX and my log out function loads on initial page download, the log out function does not respond to clicks on the log out button even though the function is referencing the log out button's ID.

What is the best way to have my log out function recognize the AJAX loaded log out button? My initial thought is to use a mouseover event on the command center div to encapsulate my log out function so that after the user logs in and moves the cursor over the AJAX loaded command center, the function looks for the log out DIV ID based on the current HTML. The drawback would be that the function would be called every time the user hovers over the command center, even if they are not looking to log out.

Is there a more straight-forward solution to this?

Upvotes: 2

Views: 107

Answers (2)

jjnguy
jjnguy

Reputation: 138874

What you want to do is use jQuery's on() function.

The code might look like:

$('body').on('click', '#log-out-button-id', function(){
    // logout code
});

Essentially, you attach the event to an element on your page that will not be changing. For performance reasons, you should use the closest stable parent element possible. (In your case that's probably '#command-center'.

Upvotes: 3

mgibsonbr
mgibsonbr

Reputation: 22007

You can use jQuery .on function on body (or, more narrowly, on your command center), passing your log out button as the selector. This way, it will execute whenever that button is present - whether it was already there or added in the future:

$("body").on("click", "#logout", function(event){
    // Your code
});

Upvotes: 2

Related Questions