Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't select element after ajax load

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!

like image 435
user2801463 Avatar asked Nov 11 '22 21:11

user2801463


1 Answers

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 :)

like image 113
yuewu Avatar answered Nov 15 '22 06:11

yuewu