JQuery cannot select item after ajax load

After many studies, I did not find the answer. I am using the wordpress theme Twenty Twelve and it seems to load pages through ajax requests. I have a button (# header-navigation-link) that shows and hides another element on my page. It works on loading the first page without ajax calls, but when I go 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!' ); }); 

A warning always appears on all ajax loaded pages, so it finds a button, not an item to show and hide. I also tried swapping two, so you press # nav-mobile-wrapper to switch # header-navigation-link, and the same thing happens just the opposite.

What am I missing for targeting # nav-mobile-wrapper in this function?

Thanks to everyone who can help!

+6
source share
2 answers

If you know the identifier, you do not need to find it again, just select it.

  $(document).on('click', "#header-navigation-link", function () { $("#nav-mobile-wrapper").fadeToggle(); alert( 'Success!' ); }); 
+1
source

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 "area". For instance:

 $( 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 loading and #nav-mobile-wrapper 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 does not work, simply because it cannot 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.

By the way, I think

 $("#header-navigation-link").on('click',function(){ // you code }); 

is an easier way to write and read :)

+1
source

Source: https://habr.com/ru/post/954310/


All Articles