I am currently working on a website that has a logout button which gets dynamically inserted into a sidebar whenever the window reaches a certain size. When I click on the log out button I want to call the method logOut();
I looked over these other posts and the solutions don't seem to be working for me. The method gets called if I click on the element while it's on the main page, but when I resize the window and the element gets "re-added" to the webpage it doesn't do anything (The ID selector is the right one because the style is all there).
$(document).ready(function()
{
$(document).on("click", "#btnLogOut", function()
{
logOut();
});
});
I expected the logOut()
method to be called after clicking on the anchor tag, but it doesn't do anything even if the .on()
method is supossed to take care of dynamically created elements
EDIT: This is how I re-add the element to the page after resizing. The nav element that includes the logout anchor tag is made into a list by a navList();
method and then gets appended to the body. I made sure to specify that the logout button needs to keep its ID. Only going to add the code relevant to the log out button.
$.fn.navList = function() {
var $this = $(this);
$a = $this.find('a'),
b = [];
$a.each(function() {
var $this = $(this),
indent = Math.max(0, $this.parents('li').length - 1),
href = $this.attr('href'),
target = $this.attr('target');
if($a.attr("id") === "btnLogOut") {
console.log($a);
b.push(
'<a ' +
'id="btnLogOut" ' +
'class="link depth-' + indent + '"' +
( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
'>' +
$this.text() +
'</a>'
);
}
});
return b.join('');
};
$(
'<div id="navPanel">' +
'<nav>' +
$('#btns').navList() +
'</nav>' +
'</div>'
)
.appendTo($body)