I'm using the WordPress theme TwentyTwelve and it seems to load pages via ajax requests. I have a button (#header-navigation-link) that shows and hides another element on my page. It works on the first page load without ajax calls, but when I navigate to another page ajax loads it, and my program can no longer find #nav-mobile-wrapper.
$(document).on('click', "#header-navigation-link", function () {
$(document).find("#nav-mobile-wrapper").fadeToggle();
alert( 'Success!' );
});
On all the ajax loaded pages the alert always pops up, so it's finding the button, just not the element to show and hide. I also tried swapping the two so you click on #nav-mobile-wrapper to toggle #header-navigation-link, and the same thing happens just vise versa.
What am I missing to target #nav-mobile-wrapper in this function?
Thanks to anyone that can help!
Is this element("#nav-mobile-wrapper") also generated by ajax? If so, make sure your click function and the place where this element is generated are in the same 'scope'. For example:
$( document ).ready(function() {
$.ajax({
// this is where you send the ajax request to server
}).done(function(response){
//because you said, it loaded page via ajax request, so page's loading and #nav-mobile-wrapper's generating probably happened here
// If so, try put your click function here, inside the 'done' block!
$(document).on('click', "#header-navigation-link", function(){
// your stuff
});
})
I think why your function doesn't work is simply because it can't find the #nav-mobile-wrapper element. Without your code this is the best guess I can have. Anyway, let me know if you still have this problem.
BTW, I think
$("#header-navigation-link").on('click',function(){
// you code
});
is an easier way to write and read :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With