0

I know This is a very common problem and there are tons of such questions which are already answered even I've solved such problems many times, But This time I'm stuck at this point. I tried to apply many solutions but nothing worked for me.

This is how my JS looks like:

jQuery(document).ready(function($){
    avHomePageThumbnails();
    var slideIndex = 0; showSlides();


    function avHomePageThumbnails(){
        let homePagePosts = JSON.parse(posts_data);
        homePagePosts.map( homePagePost => {
            let screenID = homePagePost.query_vars.meta_value;
            if(homePagePost.posts.length > 0){
                homePagePost.posts.map(( post, i ) => {
                    let postID = post.ID;
                    let postURl = post.guid;
                    $.post(ajax_url, {
                    action: "av_get_post_data_by_id",
                    id: postID
                    }, function(resp){
                        //console.log(resp, screenID);
                        resp = JSON.parse(resp);
                        let data = ''+
                        '<div class="mySlides fade">'+
                            '<a href="'+postURl+'">'+
                                '<img src="'+resp.image+'" style="width:100%">'+
                                '<div class="text">'+resp.title+'</div>'+
                            '</a>'+
                        '</div>';
                        $(".home-screen-thumb-container #"+screenID).append(data);

                    });
                } );
            }
        });
        //console.log(homePagePosts);
    }


function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    //var slides = $(".home-screen-thumb-container").find(".mySlides");
    console.log(slides);
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display="none";  
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}  

    slides[slideIndex-1].style.display = "block";  
    setTimeout(showSlides, 2000); // Change image every 2 seconds
}
});

Here I'm not able to select the div mySlides in showSlides()

Waeez
  • 289
  • 4
  • 12
  • 29

2 Answers2

1

At the time at which you call showSlides(), your other function avHomePageThumbnails() has not yet completed its (asynchronous) ajax-call.

Your solution is to either call showSlides() from your ajax-call ($.post()) its callback function (after that part that adds the div). Or (much better), make avHomePageThumbnails() return a promise, and have showSlides() called after the promise completes.

Quick intro to promises here: https://developers.google.com/web/fundamentals/primers/promises

1

ShowSlides() must be called after the appended data, because the element does not exists. your query result is not set when you called it. it's asynchronous !