Reputation: 28338
I've got a menu that's supposed to slide out on mobile units when I click a button, but it's no longer working since I made it so that the menu and button is added via AJAX instead of directly in the markup.
Here's the code:
Check the current screen (window for now) size and call the function that grabs the files:
var windowWidth = $(window).width(); //Will be screen.width later, using window for testing
if (windowWidth < 550) {
getPhpFile('mobilemenu', '#main-nav-container', 'insertAfter');
getPhpFile('mobmenuimg', '#main-nav-container', 'append');
}
This function grabs the files and calls the function that adds it to the HTML if successful:
function getPhpFile(filename, selector, method) {
$.ajax({
url : "includes/" + filename + ".php",
type: "POST",
success: function(data, textStatus, jqXHR) {
appendToHtml(data, selector, method);
},
error: function (jqXHR, textStatus, errorThrown){
console.log('Unable to get the requested files.');
}
});
}
Adds the data from the grabbed file to the HTML:
function appendToHtml(data, selector, method) {
var element = $('' + selector + '');
switch (method) {
...
//Some removed cases here
...
case 'append': element.append(data);
break;
case 'insertAfter': $(data).insertAfter(element);
break;
}
}
This is what makes the menu slide out:
$('#mobile-nav-btn').on('click', function() {
if ($('#mobile-nav-container').is(':hidden')) {
$('#mobile-nav-container').stop().show().animate({left: 0}, 'slow');
}
else {
$('#mobile-nav-container').stop().animate({left: -150}, 'slow', function() {
$('#mobile-nav-container').hide();
});
}
});
I've narrowed my search down to the fact that it can't find #mobile-nav-btn
for some reason. This because the script actually works when I use something other than the button to trigger the sliding function. I find this a bit weird though since the button and the menu are in fact in the markup when I check the console, and I don't run the script until the markup is there since it's trigged via a click event. I tried using an window.onload = init
for the sliding script as well but it did nothing. Everything is encapsulated in an $(document).ready
function as well. I'm really stuck on how to fix this so any tips on what I should do?
Upvotes: 1
Views: 117
Reputation: 1958
You are trying to bind your event to an element that doesn't exist. You can either use event delegation on a parent element of the nav button using event delegation syntax:
$('parent-element').on('click','#mobile-nav-button', function(){ ....
Or you have to bind your events after you have added those elements to the DOM.
Upvotes: 2