3

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?

2 Answers 2

5

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(); 

});
Sign up to request clarification or add additional context in comments.

Comments

3

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();

});

2 Comments

+1, nice chaining. You could make it more efficient by chaining it off of the .append(), like this: .append(data).find('.current-menu-ancestor .sub-menu').css({ display : 'block', width : '235px' }).find('li').show();
Err, so easy! There seams to be a noticeable performance loss doing this. You can see the element pop in when it gets shown. Any way to get around this? I guess it's from it loading, but the file is only a few lines of html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.