Combobreaker
Combobreaker

Reputation: 239

jQuery Functions On AJAX Loaded Content

I have an unordered list that is being loaded from an external file using $.get(). Once that is loaded, the unordered list needs to be manipulated using .show() (it is display: none; by default) when the page loads.

After reading many explanations, I understand why show() is not working on the loaded content. They say that you need to use live() (well, now .on()) to attach the a handler to an event, but all the examples are things like clicking and mousing over.

Ajax call:

$.get('/wordpress/wp-content/themes/nascar_plaza/inc/sidebar_login.php', function(data) {
    $('#site-header-nav-container > ul > li:last-child').append(data);
});

jQuery to run on loaded content:

$('.current-menu-ancestor .sub-menu').css({
    display: 'block',
    width: '235px'
});
$('.current-menu-ancestor .sub-menu li').show();

Can someone give me an example on how to get the code above to run on the content after it has been loaded?

Upvotes: 3

Views: 1027

Answers (2)

Malitta N
Malitta N

Reputation: 3423

The second part of your code (css manipulation and displaying the list) should go inside the callback function, which runs after the data is loaded.

$.get('/wordpress/wp-content/themes/nascar_plaza/inc/sidebar_login.php', function(data) {

   $('#site-header-nav-container > ul > li:last-child').append(data);

   $('.current-menu-ancestor .sub-menu').css({
       display: 'block',
       width: '235px'
   }).find('li').show();

});

Upvotes: 3

Joseph
Joseph

Reputation: 119827

like you said it: "Run after it's loaded"

var url = '/wordpress/wp-content/themes/nascar_plaza/inc/sidebar_login.php'

$.get(url, function(data) {

    //anything in this block runs after the ajax call

    $('#site-header-nav-container > ul > li:last-child').append(data);

    $('.current-menu-ancestor .sub-menu').css({ 
        display: 'block', 
        width: '235px' 
    }); 

    $('.current-menu-ancestor .sub-menu li').show(); 

});

Upvotes: 5

Related Questions